@gardenfi/core 2.3.2 → 2.3.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.
@@ -1,5 +1,5 @@
1
- "use strict";const le=require("@gardenfi/orderbook"),x=require("@gardenfi/utils"),Kl=require("varuint-bitcoin"),My=require("tiny-secp256k1"),oe=require("bitcoinjs-lib"),Dy=require("bignumber.js"),Fs=require("ecpair"),$e=require("starknet"),vf=require("yup"),Ef=require("bip39"),jy=require("bip32"),Pt=require("@coral-xyz/anchor");function uu(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const xf=uu(Kl),bt=uu(My),pe=uu(oe);var ve=(e=>(e.Idle="Idle",e.Initiate="Initiate",e.Redeem="Redeem",e.Refund="Refund",e))(ve||{});const zy="1.0.8";let ft=class bc extends Error{constructor(t,r={}){var o;const n=r.cause instanceof bc?r.cause.details:(o=r.cause)!=null&&o.message?r.cause.message:r.details,i=r.cause instanceof bc&&r.cause.docsPath||r.docsPath,s=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: https://abitype.dev${i}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${zy}`].join(`
2
- `);super(s),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.shortMessage=t}};function lr(e,t){const r=e.exec(t);return r==null?void 0:r.groups}const Yl=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Zl=/^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)?$/,Xl=/^\(.+?\).*?$/,Af=/^tuple(?<array>(\[(\d*)\])*)$/;function wc(e){let t=e.type;if(Af.test(e.type)&&"components"in e){t="(";const r=e.components.length;for(let i=0;i<r;i++){const s=e.components[i];t+=wc(s),i<r-1&&(t+=", ")}const n=lr(Af,e.type);return t+=`)${(n==null?void 0:n.array)??""}`,wc({...e,type:t})}return"indexed"in e&&e.indexed&&(t=`${t} indexed`),e.name?`${t} ${e.name}`:t}function ei(e){let t="";const r=e.length;for(let n=0;n<r;n++){const i=e[n];t+=wc(i),n!==r-1&&(t+=", ")}return t}function Gs(e){var t;return e.type==="function"?`function ${e.name}(${ei(e.inputs)})${e.stateMutability&&e.stateMutability!=="nonpayable"?` ${e.stateMutability}`:""}${(t=e.outputs)!=null&&t.length?` returns (${ei(e.outputs)})`:""}`:e.type==="event"?`event ${e.name}(${ei(e.inputs)})`:e.type==="error"?`error ${e.name}(${ei(e.inputs)})`:e.type==="constructor"?`constructor(${ei(e.inputs)})${e.stateMutability==="payable"?" payable":""}`:e.type==="fallback"?`fallback() external${e.stateMutability==="payable"?" payable":""}`:"receive() external payable"}const Jl=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function qy(e){return Jl.test(e)}function Gy(e){return lr(Jl,e)}const Ql=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function Vy(e){return Ql.test(e)}function Wy(e){return lr(Ql,e)}const ep=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function Ky(e){return ep.test(e)}function Yy(e){return lr(ep,e)}const tp=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function fu(e){return tp.test(e)}function Zy(e){return lr(tp,e)}const rp=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function Xy(e){return rp.test(e)}function Jy(e){return lr(rp,e)}const np=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function Qy(e){return np.test(e)}function em(e){return lr(np,e)}const tm=/^receive\(\) external payable$/;function rm(e){return tm.test(e)}const nm=new Set(["indexed"]),vc=new Set(["calldata","memory","storage"]);class im extends ft{constructor({signature:t}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}}class sm extends ft{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}}class om extends ft{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}}class am extends ft{constructor({param:t}){super("Invalid ABI parameter.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}}class cm extends ft{constructor({param:t,name:r}){super("Invalid ABI parameter.",{details:t,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 um extends ft{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}}class fm extends ft{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,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 dm extends ft{constructor({abiParameter:t}){super("Invalid ABI parameter.",{details:JSON.stringify(t,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}}class Vn extends ft{constructor({signature:t,type:r}){super(`Invalid ${r} signature.`,{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}}class lm extends ft{constructor({signature:t}){super("Unknown signature.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}}class pm extends ft{constructor({signature:t}){super("Invalid struct signature.",{details:t,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}}class hm extends ft{constructor({type:t}){super("Circular reference detected.",{metaMessages:[`Struct "${t}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}}class ym extends ft{constructor({current:t,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${t.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 mm(e,t,r){let n="";if(r)for(const i of Object.entries(r)){if(!i)continue;let s="";for(const o of i[1])s+=`[${o.type}${o.name?`:${o.name}`:""}]`;n+=`(${i[0]}{${s}})`}return t?`${t}:${e}${n}`:e}const Ho=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 Ec(e,t={}){if(Ky(e))return gm(e,t);if(Vy(e))return bm(e,t);if(qy(e))return wm(e,t);if(Xy(e))return vm(e,t);if(Qy(e))return Em(e);if(rm(e))return{type:"receive",stateMutability:"payable"};throw new lm({signature:e})}function gm(e,t={}){const r=Yy(e);if(!r)throw new Vn({signature:e,type:"function"});const n=St(r.parameters),i=[],s=n.length;for(let a=0;a<s;a++)i.push(Kr(n[a],{modifiers:vc,structs:t,type:"function"}));const o=[];if(r.returns){const a=St(r.returns),c=a.length;for(let f=0;f<c;f++)o.push(Kr(a[f],{modifiers:vc,structs:t,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:i,outputs:o}}function bm(e,t={}){const r=Wy(e);if(!r)throw new Vn({signature:e,type:"event"});const n=St(r.parameters),i=[],s=n.length;for(let o=0;o<s;o++)i.push(Kr(n[o],{modifiers:nm,structs:t,type:"event"}));return{name:r.name,type:"event",inputs:i}}function wm(e,t={}){const r=Gy(e);if(!r)throw new Vn({signature:e,type:"error"});const n=St(r.parameters),i=[],s=n.length;for(let o=0;o<s;o++)i.push(Kr(n[o],{structs:t,type:"error"}));return{name:r.name,type:"error",inputs:i}}function vm(e,t={}){const r=Jy(e);if(!r)throw new Vn({signature:e,type:"constructor"});const n=St(r.parameters),i=[],s=n.length;for(let o=0;o<s;o++)i.push(Kr(n[o],{structs:t,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:i}}function Em(e){const t=em(e);if(!t)throw new Vn({signature:e,type:"fallback"});return{type:"fallback",stateMutability:t.stateMutability??"nonpayable"}}const xm=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,Am=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,_m=/^u?int$/;function Kr(e,t){var d,y;const r=mm(e,t==null?void 0:t.type,t==null?void 0:t.structs);if(Ho.has(r))return Ho.get(r);const n=Xl.test(e),i=lr(n?Am:xm,e);if(!i)throw new am({param:e});if(i.name&&Pm(i.name))throw new cm({param:e,name:i.name});const s=i.name?{name:i.name}:{},o=i.modifier==="indexed"?{indexed:!0}:{},a=(t==null?void 0:t.structs)??{};let c,f={};if(n){c="tuple";const p=St(i.type),g=[],b=p.length;for(let E=0;E<b;E++)g.push(Kr(p[E],{structs:a}));f={components:g}}else if(i.type in a)c="tuple",f={components:a[i.type]};else if(_m.test(i.type))c=`${i.type}256`;else if(c=i.type,(t==null?void 0:t.type)!=="struct"&&!ip(c))throw new om({type:c});if(i.modifier){if(!((y=(d=t==null?void 0:t.modifiers)==null?void 0:d.has)!=null&&y.call(d,i.modifier)))throw new um({param:e,type:t==null?void 0:t.type,modifier:i.modifier});if(vc.has(i.modifier)&&!Tm(c,!!i.array))throw new fm({param:e,type:t==null?void 0:t.type,modifier:i.modifier})}const u={type:`${c}${i.array??""}`,...s,...o,...f};return Ho.set(r,u),u}function St(e,t=[],r="",n=0){const i=e.trim().length;for(let s=0;s<i;s++){const o=e[s],a=e.slice(s+1);switch(o){case",":return n===0?St(a,[...t,r.trim()]):St(a,t,`${r}${o}`,n);case"(":return St(a,t,`${r}${o}`,n+1);case")":return St(a,t,`${r}${o}`,n-1);default:return St(a,t,`${r}${o}`,n)}}if(r==="")return t;if(n!==0)throw new ym({current:r,depth:n});return t.push(r.trim()),t}function ip(e){return e==="address"||e==="bool"||e==="function"||e==="string"||Yl.test(e)||Zl.test(e)}const Sm=/^(?: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 Pm(e){return e==="address"||e==="bool"||e==="function"||e==="string"||e==="tuple"||Yl.test(e)||Zl.test(e)||Sm.test(e)}function Tm(e,t){return t||e==="bytes"||e==="string"||e==="tuple"}function sp(e){const t={},r=e.length;for(let o=0;o<r;o++){const a=e[o];if(!fu(a))continue;const c=Zy(a);if(!c)throw new Vn({signature:a,type:"struct"});const f=c.properties.split(";"),u=[],d=f.length;for(let y=0;y<d;y++){const g=f[y].trim();if(!g)continue;const b=Kr(g,{type:"struct"});u.push(b)}if(!u.length)throw new pm({signature:a});t[c.name]=u}const n={},i=Object.entries(t),s=i.length;for(let o=0;o<s;o++){const[a,c]=i[o];n[a]=op(c,t)}return n}const Im=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function op(e,t,r=new Set){const n=[],i=e.length;for(let s=0;s<i;s++){const o=e[s];if(Xl.test(o.type))n.push(o);else{const c=lr(Im,o.type);if(!(c!=null&&c.type))throw new dm({abiParameter:o});const{array:f,type:u}=c;if(u in t){if(r.has(u))throw new hm({type:u});n.push({...o,type:`tuple${f??""}`,components:op(t[u]??[],t,new Set([...r,u]))})}else if(ip(u))n.push(o);else throw new sm({type:u})}}return n}function ap(e){const t=sp(e),r=[],n=e.length;for(let i=0;i<n;i++){const s=e[i];fu(s)||r.push(Ec(s,t))}return r}function _f(e){let t;if(typeof e=="string")t=Ec(e);else{const r=sp(e),n=e.length;for(let i=0;i<n;i++){const s=e[i];if(!fu(s)){t=Ec(s,r);break}}}if(!t)throw new im({signature:e});return t}function ee(e,t,r){const n=e[t.name];if(typeof n=="function")return n;const i=e[r];return typeof i=="function"?i:s=>t(e,s)}function Tt(e,{includeName:t=!1}={}){if(e.type!=="function"&&e.type!=="event"&&e.type!=="error")throw new Dm(e.type);return`${e.name}(${Js(e.inputs,{includeName:t})})`}function Js(e,{includeName:t=!1}={}){return e?e.map(r=>km(r,{includeName:t})).join(t?", ":","):""}function km(e,{includeName:t}){return e.type.startsWith("tuple")?`(${Js(e.components,{includeName:t})})${e.type.slice(5)}`:e.type+(t&&e.name?` ${e.name}`:"")}function It(e,{strict:t=!0}={}){return!e||typeof e!="string"?!1:t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}function Se(e){return It(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}const cp="2.31.7";let ti={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${cp}`},D=class xc extends Error{constructor(t,r={}){var a;const n=(()=>{var c;return r.cause instanceof xc?r.cause.details:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),i=r.cause instanceof xc&&r.cause.docsPath||r.docsPath,s=(a=ti.getDocsUrl)==null?void 0:a.call(ti,{...r,docsPath:i}),o=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...n?[`Details: ${n}`]:[],...ti.version?[`Version: ${ti.version}`]:[]].join(`
1
+ "use strict";const le=require("@gardenfi/orderbook"),x=require("@gardenfi/utils"),Kl=require("varuint-bitcoin"),My=require("tiny-secp256k1"),oe=require("bitcoinjs-lib"),Dy=require("bignumber.js"),Fs=require("ecpair"),$e=require("starknet"),vf=require("yup"),Ef=require("bip39"),jy=require("bip32"),Pt=require("@coral-xyz/anchor");function uu(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const xf=uu(Kl),wt=uu(My),pe=uu(oe);var ve=(e=>(e.Idle="Idle",e.Initiate="Initiate",e.Redeem="Redeem",e.Refund="Refund",e))(ve||{});const zy="1.0.8";let dt=class bc extends Error{constructor(t,r={}){var o;const n=r.cause instanceof bc?r.cause.details:(o=r.cause)!=null&&o.message?r.cause.message:r.details,i=r.cause instanceof bc&&r.cause.docsPath||r.docsPath,s=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: https://abitype.dev${i}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${zy}`].join(`
2
+ `);super(s),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.shortMessage=t}};function lr(e,t){const r=e.exec(t);return r==null?void 0:r.groups}const Yl=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Zl=/^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)?$/,Xl=/^\(.+?\).*?$/,Af=/^tuple(?<array>(\[(\d*)\])*)$/;function wc(e){let t=e.type;if(Af.test(e.type)&&"components"in e){t="(";const r=e.components.length;for(let i=0;i<r;i++){const s=e.components[i];t+=wc(s),i<r-1&&(t+=", ")}const n=lr(Af,e.type);return t+=`)${(n==null?void 0:n.array)??""}`,wc({...e,type:t})}return"indexed"in e&&e.indexed&&(t=`${t} indexed`),e.name?`${t} ${e.name}`:t}function ei(e){let t="";const r=e.length;for(let n=0;n<r;n++){const i=e[n];t+=wc(i),n!==r-1&&(t+=", ")}return t}function Gs(e){var t;return e.type==="function"?`function ${e.name}(${ei(e.inputs)})${e.stateMutability&&e.stateMutability!=="nonpayable"?` ${e.stateMutability}`:""}${(t=e.outputs)!=null&&t.length?` returns (${ei(e.outputs)})`:""}`:e.type==="event"?`event ${e.name}(${ei(e.inputs)})`:e.type==="error"?`error ${e.name}(${ei(e.inputs)})`:e.type==="constructor"?`constructor(${ei(e.inputs)})${e.stateMutability==="payable"?" payable":""}`:e.type==="fallback"?`fallback() external${e.stateMutability==="payable"?" payable":""}`:"receive() external payable"}const Jl=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function qy(e){return Jl.test(e)}function Gy(e){return lr(Jl,e)}const Ql=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function Vy(e){return Ql.test(e)}function Wy(e){return lr(Ql,e)}const ep=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function Ky(e){return ep.test(e)}function Yy(e){return lr(ep,e)}const tp=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function fu(e){return tp.test(e)}function Zy(e){return lr(tp,e)}const rp=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function Xy(e){return rp.test(e)}function Jy(e){return lr(rp,e)}const np=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function Qy(e){return np.test(e)}function em(e){return lr(np,e)}const tm=/^receive\(\) external payable$/;function rm(e){return tm.test(e)}const nm=new Set(["indexed"]),vc=new Set(["calldata","memory","storage"]);class im extends dt{constructor({signature:t}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}}class sm extends dt{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}}class om extends dt{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}}class am extends dt{constructor({param:t}){super("Invalid ABI parameter.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}}class cm extends dt{constructor({param:t,name:r}){super("Invalid ABI parameter.",{details:t,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 um extends dt{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}}class fm extends dt{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,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 dm extends dt{constructor({abiParameter:t}){super("Invalid ABI parameter.",{details:JSON.stringify(t,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}}class Vn extends dt{constructor({signature:t,type:r}){super(`Invalid ${r} signature.`,{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}}class lm extends dt{constructor({signature:t}){super("Unknown signature.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}}class pm extends dt{constructor({signature:t}){super("Invalid struct signature.",{details:t,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}}class hm extends dt{constructor({type:t}){super("Circular reference detected.",{metaMessages:[`Struct "${t}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}}class ym extends dt{constructor({current:t,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${t.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 mm(e,t,r){let n="";if(r)for(const i of Object.entries(r)){if(!i)continue;let s="";for(const o of i[1])s+=`[${o.type}${o.name?`:${o.name}`:""}]`;n+=`(${i[0]}{${s}})`}return t?`${t}:${e}${n}`:e}const Ho=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 Ec(e,t={}){if(Ky(e))return gm(e,t);if(Vy(e))return bm(e,t);if(qy(e))return wm(e,t);if(Xy(e))return vm(e,t);if(Qy(e))return Em(e);if(rm(e))return{type:"receive",stateMutability:"payable"};throw new lm({signature:e})}function gm(e,t={}){const r=Yy(e);if(!r)throw new Vn({signature:e,type:"function"});const n=St(r.parameters),i=[],s=n.length;for(let a=0;a<s;a++)i.push(Kr(n[a],{modifiers:vc,structs:t,type:"function"}));const o=[];if(r.returns){const a=St(r.returns),c=a.length;for(let f=0;f<c;f++)o.push(Kr(a[f],{modifiers:vc,structs:t,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:i,outputs:o}}function bm(e,t={}){const r=Wy(e);if(!r)throw new Vn({signature:e,type:"event"});const n=St(r.parameters),i=[],s=n.length;for(let o=0;o<s;o++)i.push(Kr(n[o],{modifiers:nm,structs:t,type:"event"}));return{name:r.name,type:"event",inputs:i}}function wm(e,t={}){const r=Gy(e);if(!r)throw new Vn({signature:e,type:"error"});const n=St(r.parameters),i=[],s=n.length;for(let o=0;o<s;o++)i.push(Kr(n[o],{structs:t,type:"error"}));return{name:r.name,type:"error",inputs:i}}function vm(e,t={}){const r=Jy(e);if(!r)throw new Vn({signature:e,type:"constructor"});const n=St(r.parameters),i=[],s=n.length;for(let o=0;o<s;o++)i.push(Kr(n[o],{structs:t,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:i}}function Em(e){const t=em(e);if(!t)throw new Vn({signature:e,type:"fallback"});return{type:"fallback",stateMutability:t.stateMutability??"nonpayable"}}const xm=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,Am=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,_m=/^u?int$/;function Kr(e,t){var d,y;const r=mm(e,t==null?void 0:t.type,t==null?void 0:t.structs);if(Ho.has(r))return Ho.get(r);const n=Xl.test(e),i=lr(n?Am:xm,e);if(!i)throw new am({param:e});if(i.name&&Pm(i.name))throw new cm({param:e,name:i.name});const s=i.name?{name:i.name}:{},o=i.modifier==="indexed"?{indexed:!0}:{},a=(t==null?void 0:t.structs)??{};let c,f={};if(n){c="tuple";const p=St(i.type),g=[],b=p.length;for(let E=0;E<b;E++)g.push(Kr(p[E],{structs:a}));f={components:g}}else if(i.type in a)c="tuple",f={components:a[i.type]};else if(_m.test(i.type))c=`${i.type}256`;else if(c=i.type,(t==null?void 0:t.type)!=="struct"&&!ip(c))throw new om({type:c});if(i.modifier){if(!((y=(d=t==null?void 0:t.modifiers)==null?void 0:d.has)!=null&&y.call(d,i.modifier)))throw new um({param:e,type:t==null?void 0:t.type,modifier:i.modifier});if(vc.has(i.modifier)&&!Tm(c,!!i.array))throw new fm({param:e,type:t==null?void 0:t.type,modifier:i.modifier})}const u={type:`${c}${i.array??""}`,...s,...o,...f};return Ho.set(r,u),u}function St(e,t=[],r="",n=0){const i=e.trim().length;for(let s=0;s<i;s++){const o=e[s],a=e.slice(s+1);switch(o){case",":return n===0?St(a,[...t,r.trim()]):St(a,t,`${r}${o}`,n);case"(":return St(a,t,`${r}${o}`,n+1);case")":return St(a,t,`${r}${o}`,n-1);default:return St(a,t,`${r}${o}`,n)}}if(r==="")return t;if(n!==0)throw new ym({current:r,depth:n});return t.push(r.trim()),t}function ip(e){return e==="address"||e==="bool"||e==="function"||e==="string"||Yl.test(e)||Zl.test(e)}const Sm=/^(?: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 Pm(e){return e==="address"||e==="bool"||e==="function"||e==="string"||e==="tuple"||Yl.test(e)||Zl.test(e)||Sm.test(e)}function Tm(e,t){return t||e==="bytes"||e==="string"||e==="tuple"}function sp(e){const t={},r=e.length;for(let o=0;o<r;o++){const a=e[o];if(!fu(a))continue;const c=Zy(a);if(!c)throw new Vn({signature:a,type:"struct"});const f=c.properties.split(";"),u=[],d=f.length;for(let y=0;y<d;y++){const g=f[y].trim();if(!g)continue;const b=Kr(g,{type:"struct"});u.push(b)}if(!u.length)throw new pm({signature:a});t[c.name]=u}const n={},i=Object.entries(t),s=i.length;for(let o=0;o<s;o++){const[a,c]=i[o];n[a]=op(c,t)}return n}const Im=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function op(e,t,r=new Set){const n=[],i=e.length;for(let s=0;s<i;s++){const o=e[s];if(Xl.test(o.type))n.push(o);else{const c=lr(Im,o.type);if(!(c!=null&&c.type))throw new dm({abiParameter:o});const{array:f,type:u}=c;if(u in t){if(r.has(u))throw new hm({type:u});n.push({...o,type:`tuple${f??""}`,components:op(t[u]??[],t,new Set([...r,u]))})}else if(ip(u))n.push(o);else throw new sm({type:u})}}return n}function ap(e){const t=sp(e),r=[],n=e.length;for(let i=0;i<n;i++){const s=e[i];fu(s)||r.push(Ec(s,t))}return r}function _f(e){let t;if(typeof e=="string")t=Ec(e);else{const r=sp(e),n=e.length;for(let i=0;i<n;i++){const s=e[i];if(!fu(s)){t=Ec(s,r);break}}}if(!t)throw new im({signature:e});return t}function ee(e,t,r){const n=e[t.name];if(typeof n=="function")return n;const i=e[r];return typeof i=="function"?i:s=>t(e,s)}function Tt(e,{includeName:t=!1}={}){if(e.type!=="function"&&e.type!=="event"&&e.type!=="error")throw new Dm(e.type);return`${e.name}(${Js(e.inputs,{includeName:t})})`}function Js(e,{includeName:t=!1}={}){return e?e.map(r=>km(r,{includeName:t})).join(t?", ":","):""}function km(e,{includeName:t}){return e.type.startsWith("tuple")?`(${Js(e.components,{includeName:t})})${e.type.slice(5)}`:e.type+(t&&e.name?` ${e.name}`:"")}function It(e,{strict:t=!0}={}){return!e||typeof e!="string"?!1:t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}function Se(e){return It(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}const cp="2.31.7";let ti={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${cp}`},D=class xc extends Error{constructor(t,r={}){var a;const n=(()=>{var c;return r.cause instanceof xc?r.cause.details:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),i=r.cause instanceof xc&&r.cause.docsPath||r.docsPath,s=(a=ti.getDocsUrl)==null?void 0:a.call(ti,{...r,docsPath:i}),o=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...n?[`Details: ${n}`]:[],...ti.version?[`Version: ${ti.version}`]:[]].join(`
3
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=i,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=t,this.version=cp}walk(t){return up(this,t)}};function up(e,t){return t!=null&&t(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause!==void 0?up(e.cause,t):t?null:e}class Bm extends D{constructor({docsPath:t}){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
4
  `),{docsPath:t,name:"AbiConstructorNotFoundError"})}}class Sf extends D{constructor({docsPath:t}){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
5
  `),{docsPath:t,name:"AbiConstructorParamsNotFoundError"})}}class fp extends D{constructor({data:t,params:r,size:n}){super([`Data size of ${n} bytes is too small for given parameters.`].join(`
@@ -19,7 +19,7 @@
19
19
  `),{docsPath:r,name:"InvalidAbiEncodingType"})}}class Mm extends D{constructor(t,{docsPath:r}){super([`Type "${t}" is not a valid decoding type.`,"Please provide a valid ABI type."].join(`
20
20
  `),{docsPath:r,name:"InvalidAbiDecodingType"})}}let hp=class extends D{constructor(t){super([`Value "${t}" is not a valid array.`].join(`
21
21
  `),{name:"InvalidArrayError"})}};class Dm extends D{constructor(t){super([`"${t}" is not a valid definition type.`,'Valid types: "function", "event", "error"'].join(`
22
- `),{name:"InvalidDefinitionTypeError"})}}class jm extends D{constructor(t){super(`Filter type "${t}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}let yp=class extends D{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${t}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}},mp=class extends D{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${t}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}};class If extends D{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} is expected to be ${r} ${n} long, but is ${t} ${n} long.`,{name:"InvalidBytesLengthError"})}}function Wn(e,{dir:t,size:r=32}={}){return typeof e=="string"?Tr(e,{dir:t,size:r}):zm(e,{dir:t,size:r})}function Tr(e,{dir:t,size:r=32}={}){if(r===null)return e;const n=e.replace("0x","");if(n.length>r*2)throw new mp({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[t==="right"?"padEnd":"padStart"](r*2,"0")}`}function zm(e,{dir:t,size:r=32}={}){if(r===null)return e;if(e.length>r)throw new mp({size:e.length,targetSize:r,type:"bytes"});const n=new Uint8Array(r);for(let i=0;i<r;i++){const s=t==="right";n[s?i:r-i-1]=e[s?i:e.length-i-1]}return n}let gp=class extends D{constructor({max:t,min:r,signed:n,size:i,value:s}){super(`Number "${s}" is not in safe ${i?`${i*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${t?`(${r} to ${t})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}};class qm extends D{constructor(t){super(`Bytes value "${t}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}}class Gm extends D{constructor(t){super(`Hex value "${t}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`,{name:"InvalidHexBooleanError"})}}let Vm=class extends D{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${t} bytes.`,{name:"SizeOverflowError"})}};function wt(e,{dir:t="left"}={}){let r=typeof e=="string"?e.replace("0x",""):e,n=0;for(let i=0;i<r.length-1&&r[t==="left"?i:r.length-i-1].toString()==="0";i++)n++;return r=t==="left"?r.slice(n):r.slice(0,r.length-n),typeof e=="string"?(r.length===1&&t==="right"&&(r=`${r}0`),`0x${r.length%2===1?`0${r}`:r}`):r}function Ot(e,{size:t}){if(Se(e)>t)throw new Vm({givenSize:Se(e),maxSize:t})}function Ue(e,t={}){const{signed:r}=t;t.size&&Ot(e,{size:t.size});const n=BigInt(e);if(!r)return n;const i=(e.length-2)/2,s=(1n<<BigInt(i)*8n-1n)-1n;return n<=s?n:n-BigInt(`0x${"f".padStart(i*2,"f")}`)-1n}function Wm(e,t={}){let r=e;if(t.size&&(Ot(r,{size:t.size}),r=wt(r)),wt(r)==="0x00")return!1;if(wt(r)==="0x01")return!0;throw new Gm(r)}function vt(e,t={}){return Number(Ue(e,t))}const Km=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function je(e,t={}){return typeof e=="number"||typeof e=="bigint"?K(e,t):typeof e=="string"?Rn(e,t):typeof e=="boolean"?bp(e,t):Ce(e,t)}function bp(e,t={}){const r=`0x${Number(e)}`;return typeof t.size=="number"?(Ot(r,{size:t.size}),Wn(r,{size:t.size})):r}function Ce(e,t={}){let r="";for(let i=0;i<e.length;i++)r+=Km[e[i]];const n=`0x${r}`;return typeof t.size=="number"?(Ot(n,{size:t.size}),Wn(n,{dir:"right",size:t.size})):n}function K(e,t={}){const{signed:r,size:n}=t,i=BigInt(e);let s;n?r?s=(1n<<BigInt(n)*8n-1n)-1n:s=2n**(BigInt(n)*8n)-1n:typeof e=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&r?-s-1n:0;if(s&&i>s||i<o){const c=typeof e=="bigint"?"n":"";throw new gp({max:s?`${s}${c}`:void 0,min:`${o}${c}`,signed:r,size:n,value:`${e}${c}`})}const a=`0x${(r&&i<0?(1n<<BigInt(n*8))+BigInt(i):i).toString(16)}`;return n?Wn(a,{size:n}):a}const Ym=new TextEncoder;function Rn(e,t={}){const r=Ym.encode(e);return Ce(r,t)}const Zm=new TextEncoder;function Kn(e,t={}){return typeof e=="number"||typeof e=="bigint"?Jm(e,t):typeof e=="boolean"?Xm(e,t):It(e)?kt(e,t):zr(e,t)}function Xm(e,t={}){const r=new Uint8Array(1);return r[0]=Number(e),typeof t.size=="number"?(Ot(r,{size:t.size}),Wn(r,{size:t.size})):r}const Yt={zero:48,nine:57,A:65,F:70,a:97,f:102};function kf(e){if(e>=Yt.zero&&e<=Yt.nine)return e-Yt.zero;if(e>=Yt.A&&e<=Yt.F)return e-(Yt.A-10);if(e>=Yt.a&&e<=Yt.f)return e-(Yt.a-10)}function kt(e,t={}){let r=e;t.size&&(Ot(r,{size:t.size}),r=Wn(r,{dir:"right",size:t.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);const i=n.length/2,s=new Uint8Array(i);for(let o=0,a=0;o<i;o++){const c=kf(n.charCodeAt(a++)),f=kf(n.charCodeAt(a++));if(c===void 0||f===void 0)throw new D(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);s[o]=c*16+f}return s}function Jm(e,t){const r=K(e,t);return kt(r)}function zr(e,t={}){const r=Zm.encode(e);return typeof t.size=="number"?(Ot(r,{size:t.size}),Wn(r,{dir:"right",size:t.size})):r}const ys=BigInt(2**32-1),Bf=BigInt(32);function Qm(e,t=!1){return t?{h:Number(e&ys),l:Number(e>>Bf&ys)}:{h:Number(e>>Bf&ys)|0,l:Number(e&ys)|0}}function eg(e,t=!1){const r=e.length;let n=new Uint32Array(r),i=new Uint32Array(r);for(let s=0;s<r;s++){const{h:o,l:a}=Qm(e[s],t);[n[s],i[s]]=[o,a]}return[n,i]}const tg=(e,t,r)=>e<<r|t>>>32-r,rg=(e,t,r)=>t<<r|e>>>32-r,ng=(e,t,r)=>t<<r-32|e>>>64-r,ig=(e,t,r)=>e<<r-32|t>>>64-r,pn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function du(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Si(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Bt(e,...t){if(!du(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function sg(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Si(e.outputLen),Si(e.blockLen)}function Nn(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function wp(e,t){Bt(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function og(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Or(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Lo(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ft(e,t){return e<<32-t|e>>>t}function ms(e,t){return e<<t|e>>>32-t>>>0}const ag=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function cg(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function ug(e){for(let t=0;t<e.length;t++)e[t]=cg(e[t]);return e}const Of=ag?e=>e:ug,vp=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",fg=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Pi(e){if(Bt(e),vp)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=fg[e[r]];return t}const Zt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Cf(e){if(e>=Zt._0&&e<=Zt._9)return e-Zt._0;if(e>=Zt.A&&e<=Zt.F)return e-(Zt.A-10);if(e>=Zt.a&&e<=Zt.f)return e-(Zt.a-10)}function lu(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(vp)return Uint8Array.fromHex(e);const t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let i=0,s=0;i<r;i++,s+=2){const o=Cf(e.charCodeAt(s)),a=Cf(e.charCodeAt(s+1));if(o===void 0||a===void 0){const c=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[i]=o*16+a}return n}function dg(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function eo(e){return typeof e=="string"&&(e=dg(e)),Bt(e),e}function Hr(...e){let t=0;for(let n=0;n<e.length;n++){const i=e[n];Bt(i),t+=i.length}const r=new Uint8Array(t);for(let n=0,i=0;n<e.length;n++){const s=e[n];r.set(s,i),i+=s.length}return r}class pu{}function to(e){const t=n=>e().update(eo(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function lg(e=32){if(pn&&typeof pn.getRandomValues=="function")return pn.getRandomValues(new Uint8Array(e));if(pn&&typeof pn.randomBytes=="function")return Uint8Array.from(pn.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}const pg=BigInt(0),ri=BigInt(1),hg=BigInt(2),yg=BigInt(7),mg=BigInt(256),gg=BigInt(113),Ep=[],xp=[],Ap=[];for(let e=0,t=ri,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],Ep.push(2*(5*n+r)),xp.push((e+1)*(e+2)/2%64);let i=pg;for(let s=0;s<7;s++)t=(t<<ri^(t>>yg)*gg)%mg,t&hg&&(i^=ri<<(ri<<BigInt(s))-ri);Ap.push(i)}const _p=eg(Ap,!0),bg=_p[0],wg=_p[1],Rf=(e,t,r)=>r>32?ng(e,t,r):tg(e,t,r),Nf=(e,t,r)=>r>32?ig(e,t,r):rg(e,t,r);function vg(e,t=24){const r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let o=0;o<10;o++)r[o]=e[o]^e[o+10]^e[o+20]^e[o+30]^e[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,f=r[c],u=r[c+1],d=Rf(f,u,1)^r[a],y=Nf(f,u,1)^r[a+1];for(let p=0;p<50;p+=10)e[o+p]^=d,e[o+p+1]^=y}let i=e[2],s=e[3];for(let o=0;o<24;o++){const a=xp[o],c=Rf(i,s,a),f=Nf(i,s,a),u=Ep[o];i=e[u],s=e[u+1],e[u]=c,e[u+1]=f}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=e[o+a];for(let a=0;a<10;a++)e[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=bg[n],e[1]^=wg[n]}Or(r)}class hu extends pu{constructor(t,r,n,i=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.rounds=s,Si(n),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=og(this.state)}clone(){return this._cloneInto()}keccak(){Of(this.state32),vg(this.state32,this.rounds),Of(this.state32),this.posOut=0,this.pos=0}update(t){Nn(this),t=eo(t),Bt(t);const{blockLen:r,state:n}=this,i=t.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);for(let a=0;a<o;a++)n[this.pos++]^=t[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:r,pos:n,blockLen:i}=this;t[n]^=r,r&128&&n===i-1&&this.keccak(),t[i-1]^=128,this.keccak()}writeInto(t){Nn(this,!1),Bt(t),this.finish();const r=this.state,{blockLen:n}=this;for(let i=0,s=t.length;i<s;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,s-i);t.set(r.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return Si(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(wp(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Or(this.state)}_cloneInto(t){const{blockLen:r,suffix:n,outputLen:i,rounds:s,enableXOF:o}=this;return t||(t=new hu(r,n,i,o,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=n,t.outputLen=i,t.enableXOF=o,t.destroyed=this.destroyed,t}}const Eg=(e,t,r)=>to(()=>new hu(t,e,r)),Sp=Eg(1,136,256/8);function De(e,t){const r=t||"hex",n=Sp(It(e,{strict:!1})?Kn(e):e);return r==="bytes"?n:je(n)}const xg=e=>De(Kn(e));function Ag(e){return xg(e)}function _g(e){let t=!0,r="",n=0,i="",s=!1;for(let o=0;o<e.length;o++){const a=e[o];if(["(",")",","].includes(a)&&(t=!0),a==="("&&n++,a===")"&&n--,!!t){if(n===0){if(a===" "&&["event","function",""].includes(i))i="";else if(i+=a,a===")"){s=!0;break}continue}if(a===" "){e[o-1]!==","&&r!==","&&r!==",("&&(r="",t=!1);continue}i+=a,r+=a}}if(!s)throw new D("Unable to normalize signature.");return i}const Sg=e=>{const t=typeof e=="string"?e:Gs(e);return _g(t)};function Pp(e){return Ag(Sg(e))}const ro=Pp;let tt=class extends D{constructor({address:t}){super(`Address "${t}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}},no=class extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){const r=super.get(t);return super.has(t)&&r!==void 0&&(this.delete(t),super.set(t,r)),r}set(t,r){if(super.set(t,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}};const Mo=new no(8192);function Qi(e,t){if(Mo.has(`${e}.${t}`))return Mo.get(`${e}.${t}`);const r=e.substring(2).toLowerCase(),n=De(zr(r),"bytes"),i=r.split("");for(let o=0;o<40;o+=2)n[o>>1]>>4>=8&&i[o]&&(i[o]=i[o].toUpperCase()),(n[o>>1]&15)>=8&&i[o+1]&&(i[o+1]=i[o+1].toUpperCase());const s=`0x${i.join("")}`;return Mo.set(`${e}.${t}`,s),s}function Tp(e,t){if(!Fe(e,{strict:!1}))throw new tt({address:e});return Qi(e,t)}const Pg=/^0x[a-fA-F0-9]{40}$/,Do=new no(8192);function Fe(e,t){const{strict:r=!0}=t??{},n=`${e}.${r}`;if(Do.has(n))return Do.get(n);const i=Pg.test(e)?e.toLowerCase()===e?!0:r?Qi(e)===e:!0:!1;return Do.set(n,i),i}function ct(e){return typeof e[0]=="string"?Ct(e):Tg(e)}function Tg(e){let t=0;for(const i of e)t+=i.length;const r=new Uint8Array(t);let n=0;for(const i of e)r.set(i,n),n+=i.length;return r}function Ct(e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function Yr(e,t,r,{strict:n}={}){return It(e,{strict:!1})?Vs(e,t,r,{strict:n}):Bp(e,t,r,{strict:n})}function Ip(e,t){if(typeof t=="number"&&t>0&&t>Se(e)-1)throw new yp({offset:t,position:"start",size:Se(e)})}function kp(e,t,r){if(typeof t=="number"&&typeof r=="number"&&Se(e)!==r-t)throw new yp({offset:r,position:"end",size:Se(e)})}function Bp(e,t,r,{strict:n}={}){Ip(e,t);const i=e.slice(t,r);return n&&kp(i,t,r),i}function Vs(e,t,r,{strict:n}={}){Ip(e,t);const i=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;return n&&kp(i,t,r),i}const Ig=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Op=/^(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 pr(e,t){if(e.length!==t.length)throw new Rm({expectedLength:e.length,givenLength:t.length});const r=kg({params:e,values:t}),n=mu(r);return n.length===0?"0x":n}function kg({params:e,values:t}){const r=[];for(let n=0;n<e.length;n++)r.push(yu({param:e[n],value:t[n]}));return r}function yu({param:e,value:t}){const r=gu(e.type);if(r){const[n,i]=r;return Og(t,{length:n,param:{...e,type:i}})}if(e.type==="tuple")return $g(t,{param:e});if(e.type==="address")return Bg(t);if(e.type==="bool")return Rg(t);if(e.type.startsWith("uint")||e.type.startsWith("int")){const n=e.type.startsWith("int"),[,,i="256"]=Op.exec(e.type)??[];return Ng(t,{signed:n,size:Number(i)})}if(e.type.startsWith("bytes"))return Cg(t,{param:e});if(e.type==="string")return Fg(t);throw new Lm(e.type,{docsPath:"/docs/contract/encodeAbiParameters"})}function mu(e){let t=0;for(let s=0;s<e.length;s++){const{dynamic:o,encoded:a}=e[s];o?t+=32:t+=Se(a)}const r=[],n=[];let i=0;for(let s=0;s<e.length;s++){const{dynamic:o,encoded:a}=e[s];o?(r.push(K(t+i,{size:32})),n.push(a),i+=Se(a)):r.push(a)}return ct([...r,...n])}function Bg(e){if(!Fe(e))throw new tt({address:e});return{dynamic:!1,encoded:Tr(e.toLowerCase())}}function Og(e,{length:t,param:r}){const n=t===null;if(!Array.isArray(e))throw new hp(e);if(!n&&e.length!==t)throw new Om({expectedLength:t,givenLength:e.length,type:`${r.type}[${t}]`});let i=!1;const s=[];for(let o=0;o<e.length;o++){const a=yu({param:r,value:e[o]});a.dynamic&&(i=!0),s.push(a)}if(n||i){const o=mu(s);if(n){const a=K(s.length,{size:32});return{dynamic:!0,encoded:s.length>0?ct([a,o]):a}}if(i)return{dynamic:!0,encoded:o}}return{dynamic:!1,encoded:ct(s.map(({encoded:o})=>o))}}function Cg(e,{param:t}){const[,r]=t.type.split("bytes"),n=Se(e);if(!r){let i=e;return n%32!==0&&(i=Tr(i,{dir:"right",size:Math.ceil((e.length-2)/2/32)*32})),{dynamic:!0,encoded:ct([Tr(K(n,{size:32})),i])}}if(n!==Number.parseInt(r))throw new Cm({expectedSize:Number.parseInt(r),value:e});return{dynamic:!1,encoded:Tr(e,{dir:"right"})}}function Rg(e){if(typeof e!="boolean")throw new D(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Tr(bp(e))}}function Ng(e,{signed:t,size:r=256}){if(typeof r=="number"){const n=2n**(BigInt(r)-(t?1n:0n))-1n,i=t?-n-1n:0n;if(e>n||e<i)throw new gp({max:n.toString(),min:i.toString(),signed:t,size:r/8,value:e.toString()})}return{dynamic:!1,encoded:K(e,{size:32,signed:t})}}function Fg(e){const t=Rn(e),r=Math.ceil(Se(t)/32),n=[];for(let i=0;i<r;i++)n.push(Tr(Yr(t,i*32,(i+1)*32),{dir:"right"}));return{dynamic:!0,encoded:ct([Tr(K(Se(t),{size:32})),...n])}}function $g(e,{param:t}){let r=!1;const n=[];for(let i=0;i<t.components.length;i++){const s=t.components[i],o=Array.isArray(e)?i:s.name,a=yu({param:s,value:e[o]});n.push(a),a.dynamic&&(r=!0)}return{dynamic:r,encoded:r?mu(n):ct(n.map(({encoded:i})=>i))}}function gu(e){const t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}const es=e=>Yr(Pp(e),0,4);function sn(e){const{abi:t,args:r=[],name:n}=e,i=It(n,{strict:!1}),s=t.filter(a=>i?a.type==="function"?es(a)===n:a.type==="event"?ro(a)===n:!1:"name"in a&&a.name===n);if(s.length===0)return;if(s.length===1)return s[0];let o;for(const a of s){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((f,u)=>{const d="inputs"in a&&a.inputs[u];return d?Ac(f,d):!1})){if(o&&"inputs"in o&&o.inputs){const f=Cp(a.inputs,o.inputs,r);if(f)throw new Um({abiItem:a,type:f[0]},{abiItem:o,type:f[1]})}o=a}}return o||s[0]}function Ac(e,t){const r=typeof e,n=t.type;switch(n){case"address":return Fe(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in t?Object.values(t.components).every((i,s)=>Ac(Object.values(e)[s],i)):/^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"||e instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(e)&&e.every(i=>Ac(i,{...t,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function Cp(e,t,r){for(const n in e){const i=e[n],s=t[n];if(i.type==="tuple"&&s.type==="tuple"&&"components"in i&&"components"in s)return Cp(i.components,s.components,r[n]);const o=[i.type,s.type];if(o.includes("address")&&o.includes("bytes20")?!0:o.includes("address")&&o.includes("string")?Fe(r[n],{strict:!1}):o.includes("address")&&o.includes("bytes")?Fe(r[n],{strict:!1}):!1)return o}}const Ff="/docs/contract/encodeEventTopics";function ts(e){var c;const{abi:t,eventName:r,args:n}=e;let i=t[0];if(r){const f=sn({abi:t,name:r});if(!f)throw new Tf(r,{docsPath:Ff});i=f}if(i.type!=="event")throw new Tf(void 0,{docsPath:Ff});const s=Tt(i),o=ro(s);let a=[];if(n&&"inputs"in i){const f=(c=i.inputs)==null?void 0:c.filter(d=>"indexed"in d&&d.indexed),u=Array.isArray(n)?n:Object.values(n).length>0?(f==null?void 0:f.map(d=>n[d.name]))??[]:[];u.length>0&&(a=(f==null?void 0:f.map((d,y)=>Array.isArray(u[y])?u[y].map((p,g)=>$f({param:d,value:u[y][g]})):typeof u[y]<"u"&&u[y]!==null?$f({param:d,value:u[y]}):null))??[])}return[o,...a]}function $f({param:e,value:t}){if(e.type==="string"||e.type==="bytes")return De(Kn(t));if(e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))throw new jm(e.type);return pr([e],[t])}function io(e,{method:t}){var n,i;const r={};return e.transport.type==="fallback"&&((i=(n=e.transport).onResponse)==null||i.call(n,({method:s,response:o,status:a,transport:c})=>{a==="success"&&t===s&&(r[o]=c.request)})),s=>r[s]||e.request}async function bu(e,t){const{address:r,abi:n,args:i,eventName:s,fromBlock:o,strict:a,toBlock:c}=t,f=io(e,{method:"eth_newFilter"}),u=s?ts({abi:n,args:i,eventName:s}):void 0,d=await e.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof o=="bigint"?K(o):o,toBlock:typeof c=="bigint"?K(c):c,topics:u}]});return{abi:n,args:i,eventName:s,id:d,request:f(d),strict:!!a,type:"event"}}function ke(e){return typeof e=="string"?{address:e,type:"json-rpc"}:e}const Uf="/docs/contract/encodeFunctionData";function Ug(e){const{abi:t,args:r,functionName:n}=e;let i=t[0];if(n){const s=sn({abi:t,args:r,name:n});if(!s)throw new Cn(n,{docsPath:Uf});i=s}if(i.type!=="function")throw new Cn(void 0,{docsPath:Uf});return{abi:[i],functionName:es(Tt(i))}}function xt(e){const{args:t}=e,{abi:r,functionName:n}=(()=>{var a;return e.abi.length===1&&((a=e.functionName)!=null&&a.startsWith("0x"))?e:Ug(e)})(),i=r[0],s=n,o="inputs"in i&&i.inputs?pr(i.inputs,t??[]):void 0;return Ct([s,o??"0x"])}const Rp={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."},Np={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},Hg={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"};class Hf extends D{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`,{name:"NegativeOffsetError"})}}class Fp extends D{constructor({length:t,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${t}\`).`,{name:"PositionOutOfBoundsError"})}}class Lg extends D{constructor({count:t,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${t}\`).`,{name:"RecursiveReadLimitExceededError"})}}const Mg={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 Lg({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new Fp({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new Hf({offset:e});const t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new Hf({offset:e});const t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){const r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){const t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){const t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){const t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();const r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();const e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();const e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();const e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();const e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){const t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};function wu(e,{recursiveReadLimit:t=8192}={}){const r=Object.create(Mg);return r.bytes=e,r.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}function Dg(e,t={}){typeof t.size<"u"&&Ot(e,{size:t.size});const r=Ce(e,t);return Ue(r,t)}function jg(e,t={}){let r=e;if(typeof t.size<"u"&&(Ot(r,{size:t.size}),r=wt(r)),r.length>1||r[0]>1)throw new qm(r);return!!r[0]}function or(e,t={}){typeof t.size<"u"&&Ot(e,{size:t.size});const r=Ce(e,t);return vt(r,t)}function zg(e,t={}){let r=e;return typeof t.size<"u"&&(Ot(r,{size:t.size}),r=wt(r,{dir:"right"})),new TextDecoder().decode(r)}function rs(e,t){const r=typeof t=="string"?kt(t):t,n=wu(r);if(Se(r)===0&&e.length>0)throw new Ji;if(Se(t)&&Se(t)<32)throw new fp({data:typeof t=="string"?t:Ce(t),params:e,size:Se(t)});let i=0;const s=[];for(let o=0;o<e.length;++o){const a=e[o];n.setPosition(i);const[c,f]=Sn(n,a,{staticPosition:0});i+=f,s.push(c)}return s}function Sn(e,t,{staticPosition:r}){const n=gu(t.type);if(n){const[i,s]=n;return Gg(e,{...t,type:s},{length:i,staticPosition:r})}if(t.type==="tuple")return Yg(e,t,{staticPosition:r});if(t.type==="address")return qg(e);if(t.type==="bool")return Vg(e);if(t.type.startsWith("bytes"))return Wg(e,t,{staticPosition:r});if(t.type.startsWith("uint")||t.type.startsWith("int"))return Kg(e,t);if(t.type==="string")return Zg(e,{staticPosition:r});throw new Mm(t.type,{docsPath:"/docs/contract/decodeAbiParameters"})}const Lf=32,_c=32;function qg(e){const t=e.readBytes(32);return[Qi(Ce(Bp(t,-20))),32]}function Gg(e,t,{length:r,staticPosition:n}){if(!r){const o=or(e.readBytes(_c)),a=n+o,c=a+Lf;e.setPosition(a);const f=or(e.readBytes(Lf)),u=Ti(t);let d=0;const y=[];for(let p=0;p<f;++p){e.setPosition(c+(u?p*32:d));const[g,b]=Sn(e,t,{staticPosition:c});d+=b,y.push(g)}return e.setPosition(n+32),[y,32]}if(Ti(t)){const o=or(e.readBytes(_c)),a=n+o,c=[];for(let f=0;f<r;++f){e.setPosition(a+f*32);const[u]=Sn(e,t,{staticPosition:a});c.push(u)}return e.setPosition(n+32),[c,32]}let i=0;const s=[];for(let o=0;o<r;++o){const[a,c]=Sn(e,t,{staticPosition:n+i});i+=c,s.push(a)}return[s,i]}function Vg(e){return[jg(e.readBytes(32),{size:32}),32]}function Wg(e,t,{staticPosition:r}){const[n,i]=t.type.split("bytes");if(!i){const o=or(e.readBytes(32));e.setPosition(r+o);const a=or(e.readBytes(32));if(a===0)return e.setPosition(r+32),["0x",32];const c=e.readBytes(a);return e.setPosition(r+32),[Ce(c),32]}return[Ce(e.readBytes(Number.parseInt(i),32)),32]}function Kg(e,t){const r=t.type.startsWith("int"),n=Number.parseInt(t.type.split("int")[1]||"256"),i=e.readBytes(32);return[n>48?Dg(i,{signed:r}):or(i,{signed:r}),32]}function Yg(e,t,{staticPosition:r}){const n=t.components.length===0||t.components.some(({name:o})=>!o),i=n?[]:{};let s=0;if(Ti(t)){const o=or(e.readBytes(_c)),a=r+o;for(let c=0;c<t.components.length;++c){const f=t.components[c];e.setPosition(a+s);const[u,d]=Sn(e,f,{staticPosition:a});s+=d,i[n?c:f==null?void 0:f.name]=u}return e.setPosition(r+32),[i,32]}for(let o=0;o<t.components.length;++o){const a=t.components[o],[c,f]=Sn(e,a,{staticPosition:r});i[n?o:a==null?void 0:a.name]=c,s+=f}return[i,s]}function Zg(e,{staticPosition:t}){const r=or(e.readBytes(32)),n=t+r;e.setPosition(n);const i=or(e.readBytes(32));if(i===0)return e.setPosition(t+32),["",32];const s=e.readBytes(i,32),o=zg(wt(s));return e.setPosition(t+32),[o,32]}function Ti(e){var n;const{type:t}=e;if(t==="string"||t==="bytes"||t.endsWith("[]"))return!0;if(t==="tuple")return(n=e.components)==null?void 0:n.some(Ti);const r=gu(e.type);return!!(r&&Ti({...e,type:r[1]}))}function $p(e){const{abi:t,data:r}=e,n=Yr(r,0,4);if(n==="0x")throw new Ji;const s=[...t||[],Np,Hg].find(o=>o.type==="error"&&n===es(Tt(o)));if(!s)throw new dp(n,{docsPath:"/docs/contract/decodeErrorResult"});return{abiItem:s,args:"inputs"in s&&s.inputs&&s.inputs.length>0?rs(s.inputs,Yr(r,4)):void 0,errorName:s.name}}const Oe=(e,t,r)=>JSON.stringify(e,(n,i)=>typeof i=="bigint"?i.toString():i,r);function Up({abiItem:e,args:t,includeFunctionName:r=!0,includeName:n=!1}){if("name"in e&&"inputs"in e&&e.inputs)return`${r?e.name:""}(${e.inputs.map((i,s)=>`${n&&i.name?`${i.name}: `:""}${typeof t[s]=="object"?Oe(t[s]):t[s]}`).join(", ")})`}const Xg={gwei:9,wei:18},Jg={ether:-9,wei:9};function Hp(e,t){let r=e.toString();const n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(t,"0");let[i,s]=[r.slice(0,r.length-t),r.slice(r.length-t)];return s=s.replace(/(0+)$/,""),`${n?"-":""}${i||"0"}${s?`.${s}`:""}`}function vu(e,t="wei"){return Hp(e,Xg[t])}function it(e,t="wei"){return Hp(e,Jg[t])}class Qg extends D{constructor({address:t}){super(`State for account "${t}" is set multiple times.`,{name:"AccountStateConflictError"})}}class eb extends D{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}function Mf(e){return e.reduce((t,{slot:r,value:n})=>`${t} ${r}: ${n}
22
+ `),{name:"InvalidDefinitionTypeError"})}}class jm extends D{constructor(t){super(`Filter type "${t}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}let yp=class extends D{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${t}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}},mp=class extends D{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${t}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}};class If extends D{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} is expected to be ${r} ${n} long, but is ${t} ${n} long.`,{name:"InvalidBytesLengthError"})}}function Wn(e,{dir:t,size:r=32}={}){return typeof e=="string"?Tr(e,{dir:t,size:r}):zm(e,{dir:t,size:r})}function Tr(e,{dir:t,size:r=32}={}){if(r===null)return e;const n=e.replace("0x","");if(n.length>r*2)throw new mp({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[t==="right"?"padEnd":"padStart"](r*2,"0")}`}function zm(e,{dir:t,size:r=32}={}){if(r===null)return e;if(e.length>r)throw new mp({size:e.length,targetSize:r,type:"bytes"});const n=new Uint8Array(r);for(let i=0;i<r;i++){const s=t==="right";n[s?i:r-i-1]=e[s?i:e.length-i-1]}return n}let gp=class extends D{constructor({max:t,min:r,signed:n,size:i,value:s}){super(`Number "${s}" is not in safe ${i?`${i*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${t?`(${r} to ${t})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}};class qm extends D{constructor(t){super(`Bytes value "${t}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}}class Gm extends D{constructor(t){super(`Hex value "${t}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`,{name:"InvalidHexBooleanError"})}}let Vm=class extends D{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${t} bytes.`,{name:"SizeOverflowError"})}};function vt(e,{dir:t="left"}={}){let r=typeof e=="string"?e.replace("0x",""):e,n=0;for(let i=0;i<r.length-1&&r[t==="left"?i:r.length-i-1].toString()==="0";i++)n++;return r=t==="left"?r.slice(n):r.slice(0,r.length-n),typeof e=="string"?(r.length===1&&t==="right"&&(r=`${r}0`),`0x${r.length%2===1?`0${r}`:r}`):r}function Ot(e,{size:t}){if(Se(e)>t)throw new Vm({givenSize:Se(e),maxSize:t})}function Ue(e,t={}){const{signed:r}=t;t.size&&Ot(e,{size:t.size});const n=BigInt(e);if(!r)return n;const i=(e.length-2)/2,s=(1n<<BigInt(i)*8n-1n)-1n;return n<=s?n:n-BigInt(`0x${"f".padStart(i*2,"f")}`)-1n}function Wm(e,t={}){let r=e;if(t.size&&(Ot(r,{size:t.size}),r=vt(r)),vt(r)==="0x00")return!1;if(vt(r)==="0x01")return!0;throw new Gm(r)}function Et(e,t={}){return Number(Ue(e,t))}const Km=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function je(e,t={}){return typeof e=="number"||typeof e=="bigint"?K(e,t):typeof e=="string"?Rn(e,t):typeof e=="boolean"?bp(e,t):Ce(e,t)}function bp(e,t={}){const r=`0x${Number(e)}`;return typeof t.size=="number"?(Ot(r,{size:t.size}),Wn(r,{size:t.size})):r}function Ce(e,t={}){let r="";for(let i=0;i<e.length;i++)r+=Km[e[i]];const n=`0x${r}`;return typeof t.size=="number"?(Ot(n,{size:t.size}),Wn(n,{dir:"right",size:t.size})):n}function K(e,t={}){const{signed:r,size:n}=t,i=BigInt(e);let s;n?r?s=(1n<<BigInt(n)*8n-1n)-1n:s=2n**(BigInt(n)*8n)-1n:typeof e=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&r?-s-1n:0;if(s&&i>s||i<o){const c=typeof e=="bigint"?"n":"";throw new gp({max:s?`${s}${c}`:void 0,min:`${o}${c}`,signed:r,size:n,value:`${e}${c}`})}const a=`0x${(r&&i<0?(1n<<BigInt(n*8))+BigInt(i):i).toString(16)}`;return n?Wn(a,{size:n}):a}const Ym=new TextEncoder;function Rn(e,t={}){const r=Ym.encode(e);return Ce(r,t)}const Zm=new TextEncoder;function Kn(e,t={}){return typeof e=="number"||typeof e=="bigint"?Jm(e,t):typeof e=="boolean"?Xm(e,t):It(e)?kt(e,t):zr(e,t)}function Xm(e,t={}){const r=new Uint8Array(1);return r[0]=Number(e),typeof t.size=="number"?(Ot(r,{size:t.size}),Wn(r,{size:t.size})):r}const Yt={zero:48,nine:57,A:65,F:70,a:97,f:102};function kf(e){if(e>=Yt.zero&&e<=Yt.nine)return e-Yt.zero;if(e>=Yt.A&&e<=Yt.F)return e-(Yt.A-10);if(e>=Yt.a&&e<=Yt.f)return e-(Yt.a-10)}function kt(e,t={}){let r=e;t.size&&(Ot(r,{size:t.size}),r=Wn(r,{dir:"right",size:t.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);const i=n.length/2,s=new Uint8Array(i);for(let o=0,a=0;o<i;o++){const c=kf(n.charCodeAt(a++)),f=kf(n.charCodeAt(a++));if(c===void 0||f===void 0)throw new D(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);s[o]=c*16+f}return s}function Jm(e,t){const r=K(e,t);return kt(r)}function zr(e,t={}){const r=Zm.encode(e);return typeof t.size=="number"?(Ot(r,{size:t.size}),Wn(r,{dir:"right",size:t.size})):r}const ys=BigInt(2**32-1),Bf=BigInt(32);function Qm(e,t=!1){return t?{h:Number(e&ys),l:Number(e>>Bf&ys)}:{h:Number(e>>Bf&ys)|0,l:Number(e&ys)|0}}function eg(e,t=!1){const r=e.length;let n=new Uint32Array(r),i=new Uint32Array(r);for(let s=0;s<r;s++){const{h:o,l:a}=Qm(e[s],t);[n[s],i[s]]=[o,a]}return[n,i]}const tg=(e,t,r)=>e<<r|t>>>32-r,rg=(e,t,r)=>t<<r|e>>>32-r,ng=(e,t,r)=>t<<r-32|e>>>64-r,ig=(e,t,r)=>e<<r-32|t>>>64-r,pn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function du(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Si(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Bt(e,...t){if(!du(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function sg(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Si(e.outputLen),Si(e.blockLen)}function Nn(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function wp(e,t){Bt(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function og(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Or(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Lo(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ft(e,t){return e<<32-t|e>>>t}function ms(e,t){return e<<t|e>>>32-t>>>0}const ag=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function cg(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function ug(e){for(let t=0;t<e.length;t++)e[t]=cg(e[t]);return e}const Of=ag?e=>e:ug,vp=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",fg=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Pi(e){if(Bt(e),vp)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=fg[e[r]];return t}const Zt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Cf(e){if(e>=Zt._0&&e<=Zt._9)return e-Zt._0;if(e>=Zt.A&&e<=Zt.F)return e-(Zt.A-10);if(e>=Zt.a&&e<=Zt.f)return e-(Zt.a-10)}function lu(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(vp)return Uint8Array.fromHex(e);const t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let i=0,s=0;i<r;i++,s+=2){const o=Cf(e.charCodeAt(s)),a=Cf(e.charCodeAt(s+1));if(o===void 0||a===void 0){const c=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[i]=o*16+a}return n}function dg(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function eo(e){return typeof e=="string"&&(e=dg(e)),Bt(e),e}function Hr(...e){let t=0;for(let n=0;n<e.length;n++){const i=e[n];Bt(i),t+=i.length}const r=new Uint8Array(t);for(let n=0,i=0;n<e.length;n++){const s=e[n];r.set(s,i),i+=s.length}return r}class pu{}function to(e){const t=n=>e().update(eo(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function lg(e=32){if(pn&&typeof pn.getRandomValues=="function")return pn.getRandomValues(new Uint8Array(e));if(pn&&typeof pn.randomBytes=="function")return Uint8Array.from(pn.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}const pg=BigInt(0),ri=BigInt(1),hg=BigInt(2),yg=BigInt(7),mg=BigInt(256),gg=BigInt(113),Ep=[],xp=[],Ap=[];for(let e=0,t=ri,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],Ep.push(2*(5*n+r)),xp.push((e+1)*(e+2)/2%64);let i=pg;for(let s=0;s<7;s++)t=(t<<ri^(t>>yg)*gg)%mg,t&hg&&(i^=ri<<(ri<<BigInt(s))-ri);Ap.push(i)}const _p=eg(Ap,!0),bg=_p[0],wg=_p[1],Rf=(e,t,r)=>r>32?ng(e,t,r):tg(e,t,r),Nf=(e,t,r)=>r>32?ig(e,t,r):rg(e,t,r);function vg(e,t=24){const r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let o=0;o<10;o++)r[o]=e[o]^e[o+10]^e[o+20]^e[o+30]^e[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,f=r[c],u=r[c+1],d=Rf(f,u,1)^r[a],y=Nf(f,u,1)^r[a+1];for(let p=0;p<50;p+=10)e[o+p]^=d,e[o+p+1]^=y}let i=e[2],s=e[3];for(let o=0;o<24;o++){const a=xp[o],c=Rf(i,s,a),f=Nf(i,s,a),u=Ep[o];i=e[u],s=e[u+1],e[u]=c,e[u+1]=f}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=e[o+a];for(let a=0;a<10;a++)e[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=bg[n],e[1]^=wg[n]}Or(r)}class hu extends pu{constructor(t,r,n,i=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.rounds=s,Si(n),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=og(this.state)}clone(){return this._cloneInto()}keccak(){Of(this.state32),vg(this.state32,this.rounds),Of(this.state32),this.posOut=0,this.pos=0}update(t){Nn(this),t=eo(t),Bt(t);const{blockLen:r,state:n}=this,i=t.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);for(let a=0;a<o;a++)n[this.pos++]^=t[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:r,pos:n,blockLen:i}=this;t[n]^=r,r&128&&n===i-1&&this.keccak(),t[i-1]^=128,this.keccak()}writeInto(t){Nn(this,!1),Bt(t),this.finish();const r=this.state,{blockLen:n}=this;for(let i=0,s=t.length;i<s;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,s-i);t.set(r.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return Si(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(wp(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Or(this.state)}_cloneInto(t){const{blockLen:r,suffix:n,outputLen:i,rounds:s,enableXOF:o}=this;return t||(t=new hu(r,n,i,o,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=n,t.outputLen=i,t.enableXOF=o,t.destroyed=this.destroyed,t}}const Eg=(e,t,r)=>to(()=>new hu(t,e,r)),Sp=Eg(1,136,256/8);function De(e,t){const r=t||"hex",n=Sp(It(e,{strict:!1})?Kn(e):e);return r==="bytes"?n:je(n)}const xg=e=>De(Kn(e));function Ag(e){return xg(e)}function _g(e){let t=!0,r="",n=0,i="",s=!1;for(let o=0;o<e.length;o++){const a=e[o];if(["(",")",","].includes(a)&&(t=!0),a==="("&&n++,a===")"&&n--,!!t){if(n===0){if(a===" "&&["event","function",""].includes(i))i="";else if(i+=a,a===")"){s=!0;break}continue}if(a===" "){e[o-1]!==","&&r!==","&&r!==",("&&(r="",t=!1);continue}i+=a,r+=a}}if(!s)throw new D("Unable to normalize signature.");return i}const Sg=e=>{const t=typeof e=="string"?e:Gs(e);return _g(t)};function Pp(e){return Ag(Sg(e))}const ro=Pp;let tt=class extends D{constructor({address:t}){super(`Address "${t}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}},no=class extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){const r=super.get(t);return super.has(t)&&r!==void 0&&(this.delete(t),super.set(t,r)),r}set(t,r){if(super.set(t,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}};const Mo=new no(8192);function Qi(e,t){if(Mo.has(`${e}.${t}`))return Mo.get(`${e}.${t}`);const r=e.substring(2).toLowerCase(),n=De(zr(r),"bytes"),i=r.split("");for(let o=0;o<40;o+=2)n[o>>1]>>4>=8&&i[o]&&(i[o]=i[o].toUpperCase()),(n[o>>1]&15)>=8&&i[o+1]&&(i[o+1]=i[o+1].toUpperCase());const s=`0x${i.join("")}`;return Mo.set(`${e}.${t}`,s),s}function Tp(e,t){if(!Fe(e,{strict:!1}))throw new tt({address:e});return Qi(e,t)}const Pg=/^0x[a-fA-F0-9]{40}$/,Do=new no(8192);function Fe(e,t){const{strict:r=!0}=t??{},n=`${e}.${r}`;if(Do.has(n))return Do.get(n);const i=Pg.test(e)?e.toLowerCase()===e?!0:r?Qi(e)===e:!0:!1;return Do.set(n,i),i}function ut(e){return typeof e[0]=="string"?Ct(e):Tg(e)}function Tg(e){let t=0;for(const i of e)t+=i.length;const r=new Uint8Array(t);let n=0;for(const i of e)r.set(i,n),n+=i.length;return r}function Ct(e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function Yr(e,t,r,{strict:n}={}){return It(e,{strict:!1})?Vs(e,t,r,{strict:n}):Bp(e,t,r,{strict:n})}function Ip(e,t){if(typeof t=="number"&&t>0&&t>Se(e)-1)throw new yp({offset:t,position:"start",size:Se(e)})}function kp(e,t,r){if(typeof t=="number"&&typeof r=="number"&&Se(e)!==r-t)throw new yp({offset:r,position:"end",size:Se(e)})}function Bp(e,t,r,{strict:n}={}){Ip(e,t);const i=e.slice(t,r);return n&&kp(i,t,r),i}function Vs(e,t,r,{strict:n}={}){Ip(e,t);const i=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;return n&&kp(i,t,r),i}const Ig=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Op=/^(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 pr(e,t){if(e.length!==t.length)throw new Rm({expectedLength:e.length,givenLength:t.length});const r=kg({params:e,values:t}),n=mu(r);return n.length===0?"0x":n}function kg({params:e,values:t}){const r=[];for(let n=0;n<e.length;n++)r.push(yu({param:e[n],value:t[n]}));return r}function yu({param:e,value:t}){const r=gu(e.type);if(r){const[n,i]=r;return Og(t,{length:n,param:{...e,type:i}})}if(e.type==="tuple")return $g(t,{param:e});if(e.type==="address")return Bg(t);if(e.type==="bool")return Rg(t);if(e.type.startsWith("uint")||e.type.startsWith("int")){const n=e.type.startsWith("int"),[,,i="256"]=Op.exec(e.type)??[];return Ng(t,{signed:n,size:Number(i)})}if(e.type.startsWith("bytes"))return Cg(t,{param:e});if(e.type==="string")return Fg(t);throw new Lm(e.type,{docsPath:"/docs/contract/encodeAbiParameters"})}function mu(e){let t=0;for(let s=0;s<e.length;s++){const{dynamic:o,encoded:a}=e[s];o?t+=32:t+=Se(a)}const r=[],n=[];let i=0;for(let s=0;s<e.length;s++){const{dynamic:o,encoded:a}=e[s];o?(r.push(K(t+i,{size:32})),n.push(a),i+=Se(a)):r.push(a)}return ut([...r,...n])}function Bg(e){if(!Fe(e))throw new tt({address:e});return{dynamic:!1,encoded:Tr(e.toLowerCase())}}function Og(e,{length:t,param:r}){const n=t===null;if(!Array.isArray(e))throw new hp(e);if(!n&&e.length!==t)throw new Om({expectedLength:t,givenLength:e.length,type:`${r.type}[${t}]`});let i=!1;const s=[];for(let o=0;o<e.length;o++){const a=yu({param:r,value:e[o]});a.dynamic&&(i=!0),s.push(a)}if(n||i){const o=mu(s);if(n){const a=K(s.length,{size:32});return{dynamic:!0,encoded:s.length>0?ut([a,o]):a}}if(i)return{dynamic:!0,encoded:o}}return{dynamic:!1,encoded:ut(s.map(({encoded:o})=>o))}}function Cg(e,{param:t}){const[,r]=t.type.split("bytes"),n=Se(e);if(!r){let i=e;return n%32!==0&&(i=Tr(i,{dir:"right",size:Math.ceil((e.length-2)/2/32)*32})),{dynamic:!0,encoded:ut([Tr(K(n,{size:32})),i])}}if(n!==Number.parseInt(r))throw new Cm({expectedSize:Number.parseInt(r),value:e});return{dynamic:!1,encoded:Tr(e,{dir:"right"})}}function Rg(e){if(typeof e!="boolean")throw new D(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Tr(bp(e))}}function Ng(e,{signed:t,size:r=256}){if(typeof r=="number"){const n=2n**(BigInt(r)-(t?1n:0n))-1n,i=t?-n-1n:0n;if(e>n||e<i)throw new gp({max:n.toString(),min:i.toString(),signed:t,size:r/8,value:e.toString()})}return{dynamic:!1,encoded:K(e,{size:32,signed:t})}}function Fg(e){const t=Rn(e),r=Math.ceil(Se(t)/32),n=[];for(let i=0;i<r;i++)n.push(Tr(Yr(t,i*32,(i+1)*32),{dir:"right"}));return{dynamic:!0,encoded:ut([Tr(K(Se(t),{size:32})),...n])}}function $g(e,{param:t}){let r=!1;const n=[];for(let i=0;i<t.components.length;i++){const s=t.components[i],o=Array.isArray(e)?i:s.name,a=yu({param:s,value:e[o]});n.push(a),a.dynamic&&(r=!0)}return{dynamic:r,encoded:r?mu(n):ut(n.map(({encoded:i})=>i))}}function gu(e){const t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}const es=e=>Yr(Pp(e),0,4);function sn(e){const{abi:t,args:r=[],name:n}=e,i=It(n,{strict:!1}),s=t.filter(a=>i?a.type==="function"?es(a)===n:a.type==="event"?ro(a)===n:!1:"name"in a&&a.name===n);if(s.length===0)return;if(s.length===1)return s[0];let o;for(const a of s){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((f,u)=>{const d="inputs"in a&&a.inputs[u];return d?Ac(f,d):!1})){if(o&&"inputs"in o&&o.inputs){const f=Cp(a.inputs,o.inputs,r);if(f)throw new Um({abiItem:a,type:f[0]},{abiItem:o,type:f[1]})}o=a}}return o||s[0]}function Ac(e,t){const r=typeof e,n=t.type;switch(n){case"address":return Fe(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in t?Object.values(t.components).every((i,s)=>Ac(Object.values(e)[s],i)):/^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"||e instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(e)&&e.every(i=>Ac(i,{...t,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function Cp(e,t,r){for(const n in e){const i=e[n],s=t[n];if(i.type==="tuple"&&s.type==="tuple"&&"components"in i&&"components"in s)return Cp(i.components,s.components,r[n]);const o=[i.type,s.type];if(o.includes("address")&&o.includes("bytes20")?!0:o.includes("address")&&o.includes("string")?Fe(r[n],{strict:!1}):o.includes("address")&&o.includes("bytes")?Fe(r[n],{strict:!1}):!1)return o}}const Ff="/docs/contract/encodeEventTopics";function ts(e){var c;const{abi:t,eventName:r,args:n}=e;let i=t[0];if(r){const f=sn({abi:t,name:r});if(!f)throw new Tf(r,{docsPath:Ff});i=f}if(i.type!=="event")throw new Tf(void 0,{docsPath:Ff});const s=Tt(i),o=ro(s);let a=[];if(n&&"inputs"in i){const f=(c=i.inputs)==null?void 0:c.filter(d=>"indexed"in d&&d.indexed),u=Array.isArray(n)?n:Object.values(n).length>0?(f==null?void 0:f.map(d=>n[d.name]))??[]:[];u.length>0&&(a=(f==null?void 0:f.map((d,y)=>Array.isArray(u[y])?u[y].map((p,g)=>$f({param:d,value:u[y][g]})):typeof u[y]<"u"&&u[y]!==null?$f({param:d,value:u[y]}):null))??[])}return[o,...a]}function $f({param:e,value:t}){if(e.type==="string"||e.type==="bytes")return De(Kn(t));if(e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))throw new jm(e.type);return pr([e],[t])}function io(e,{method:t}){var n,i;const r={};return e.transport.type==="fallback"&&((i=(n=e.transport).onResponse)==null||i.call(n,({method:s,response:o,status:a,transport:c})=>{a==="success"&&t===s&&(r[o]=c.request)})),s=>r[s]||e.request}async function bu(e,t){const{address:r,abi:n,args:i,eventName:s,fromBlock:o,strict:a,toBlock:c}=t,f=io(e,{method:"eth_newFilter"}),u=s?ts({abi:n,args:i,eventName:s}):void 0,d=await e.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof o=="bigint"?K(o):o,toBlock:typeof c=="bigint"?K(c):c,topics:u}]});return{abi:n,args:i,eventName:s,id:d,request:f(d),strict:!!a,type:"event"}}function ke(e){return typeof e=="string"?{address:e,type:"json-rpc"}:e}const Uf="/docs/contract/encodeFunctionData";function Ug(e){const{abi:t,args:r,functionName:n}=e;let i=t[0];if(n){const s=sn({abi:t,args:r,name:n});if(!s)throw new Cn(n,{docsPath:Uf});i=s}if(i.type!=="function")throw new Cn(void 0,{docsPath:Uf});return{abi:[i],functionName:es(Tt(i))}}function At(e){const{args:t}=e,{abi:r,functionName:n}=(()=>{var a;return e.abi.length===1&&((a=e.functionName)!=null&&a.startsWith("0x"))?e:Ug(e)})(),i=r[0],s=n,o="inputs"in i&&i.inputs?pr(i.inputs,t??[]):void 0;return Ct([s,o??"0x"])}const Rp={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."},Np={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},Hg={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"};class Hf extends D{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`,{name:"NegativeOffsetError"})}}class Fp extends D{constructor({length:t,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${t}\`).`,{name:"PositionOutOfBoundsError"})}}class Lg extends D{constructor({count:t,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${t}\`).`,{name:"RecursiveReadLimitExceededError"})}}const Mg={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 Lg({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new Fp({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new Hf({offset:e});const t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new Hf({offset:e});const t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){const r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){const t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){const t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){const t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();const r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();const e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();const e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();const e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();const e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){const t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};function wu(e,{recursiveReadLimit:t=8192}={}){const r=Object.create(Mg);return r.bytes=e,r.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}function Dg(e,t={}){typeof t.size<"u"&&Ot(e,{size:t.size});const r=Ce(e,t);return Ue(r,t)}function jg(e,t={}){let r=e;if(typeof t.size<"u"&&(Ot(r,{size:t.size}),r=vt(r)),r.length>1||r[0]>1)throw new qm(r);return!!r[0]}function or(e,t={}){typeof t.size<"u"&&Ot(e,{size:t.size});const r=Ce(e,t);return Et(r,t)}function zg(e,t={}){let r=e;return typeof t.size<"u"&&(Ot(r,{size:t.size}),r=vt(r,{dir:"right"})),new TextDecoder().decode(r)}function rs(e,t){const r=typeof t=="string"?kt(t):t,n=wu(r);if(Se(r)===0&&e.length>0)throw new Ji;if(Se(t)&&Se(t)<32)throw new fp({data:typeof t=="string"?t:Ce(t),params:e,size:Se(t)});let i=0;const s=[];for(let o=0;o<e.length;++o){const a=e[o];n.setPosition(i);const[c,f]=Sn(n,a,{staticPosition:0});i+=f,s.push(c)}return s}function Sn(e,t,{staticPosition:r}){const n=gu(t.type);if(n){const[i,s]=n;return Gg(e,{...t,type:s},{length:i,staticPosition:r})}if(t.type==="tuple")return Yg(e,t,{staticPosition:r});if(t.type==="address")return qg(e);if(t.type==="bool")return Vg(e);if(t.type.startsWith("bytes"))return Wg(e,t,{staticPosition:r});if(t.type.startsWith("uint")||t.type.startsWith("int"))return Kg(e,t);if(t.type==="string")return Zg(e,{staticPosition:r});throw new Mm(t.type,{docsPath:"/docs/contract/decodeAbiParameters"})}const Lf=32,_c=32;function qg(e){const t=e.readBytes(32);return[Qi(Ce(Bp(t,-20))),32]}function Gg(e,t,{length:r,staticPosition:n}){if(!r){const o=or(e.readBytes(_c)),a=n+o,c=a+Lf;e.setPosition(a);const f=or(e.readBytes(Lf)),u=Ti(t);let d=0;const y=[];for(let p=0;p<f;++p){e.setPosition(c+(u?p*32:d));const[g,b]=Sn(e,t,{staticPosition:c});d+=b,y.push(g)}return e.setPosition(n+32),[y,32]}if(Ti(t)){const o=or(e.readBytes(_c)),a=n+o,c=[];for(let f=0;f<r;++f){e.setPosition(a+f*32);const[u]=Sn(e,t,{staticPosition:a});c.push(u)}return e.setPosition(n+32),[c,32]}let i=0;const s=[];for(let o=0;o<r;++o){const[a,c]=Sn(e,t,{staticPosition:n+i});i+=c,s.push(a)}return[s,i]}function Vg(e){return[jg(e.readBytes(32),{size:32}),32]}function Wg(e,t,{staticPosition:r}){const[n,i]=t.type.split("bytes");if(!i){const o=or(e.readBytes(32));e.setPosition(r+o);const a=or(e.readBytes(32));if(a===0)return e.setPosition(r+32),["0x",32];const c=e.readBytes(a);return e.setPosition(r+32),[Ce(c),32]}return[Ce(e.readBytes(Number.parseInt(i),32)),32]}function Kg(e,t){const r=t.type.startsWith("int"),n=Number.parseInt(t.type.split("int")[1]||"256"),i=e.readBytes(32);return[n>48?Dg(i,{signed:r}):or(i,{signed:r}),32]}function Yg(e,t,{staticPosition:r}){const n=t.components.length===0||t.components.some(({name:o})=>!o),i=n?[]:{};let s=0;if(Ti(t)){const o=or(e.readBytes(_c)),a=r+o;for(let c=0;c<t.components.length;++c){const f=t.components[c];e.setPosition(a+s);const[u,d]=Sn(e,f,{staticPosition:a});s+=d,i[n?c:f==null?void 0:f.name]=u}return e.setPosition(r+32),[i,32]}for(let o=0;o<t.components.length;++o){const a=t.components[o],[c,f]=Sn(e,a,{staticPosition:r});i[n?o:a==null?void 0:a.name]=c,s+=f}return[i,s]}function Zg(e,{staticPosition:t}){const r=or(e.readBytes(32)),n=t+r;e.setPosition(n);const i=or(e.readBytes(32));if(i===0)return e.setPosition(t+32),["",32];const s=e.readBytes(i,32),o=zg(vt(s));return e.setPosition(t+32),[o,32]}function Ti(e){var n;const{type:t}=e;if(t==="string"||t==="bytes"||t.endsWith("[]"))return!0;if(t==="tuple")return(n=e.components)==null?void 0:n.some(Ti);const r=gu(e.type);return!!(r&&Ti({...e,type:r[1]}))}function $p(e){const{abi:t,data:r}=e,n=Yr(r,0,4);if(n==="0x")throw new Ji;const s=[...t||[],Np,Hg].find(o=>o.type==="error"&&n===es(Tt(o)));if(!s)throw new dp(n,{docsPath:"/docs/contract/decodeErrorResult"});return{abiItem:s,args:"inputs"in s&&s.inputs&&s.inputs.length>0?rs(s.inputs,Yr(r,4)):void 0,errorName:s.name}}const Oe=(e,t,r)=>JSON.stringify(e,(n,i)=>typeof i=="bigint"?i.toString():i,r);function Up({abiItem:e,args:t,includeFunctionName:r=!0,includeName:n=!1}){if("name"in e&&"inputs"in e&&e.inputs)return`${r?e.name:""}(${e.inputs.map((i,s)=>`${n&&i.name?`${i.name}: `:""}${typeof t[s]=="object"?Oe(t[s]):t[s]}`).join(", ")})`}const Xg={gwei:9,wei:18},Jg={ether:-9,wei:9};function Hp(e,t){let r=e.toString();const n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(t,"0");let[i,s]=[r.slice(0,r.length-t),r.slice(r.length-t)];return s=s.replace(/(0+)$/,""),`${n?"-":""}${i||"0"}${s?`.${s}`:""}`}function vu(e,t="wei"){return Hp(e,Xg[t])}function it(e,t="wei"){return Hp(e,Jg[t])}class Qg extends D{constructor({address:t}){super(`State for account "${t}" is set multiple times.`,{name:"AccountStateConflictError"})}}class eb extends D{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}function Mf(e){return e.reduce((t,{slot:r,value:n})=>`${t} ${r}: ${n}
23
23
  `,"")}function tb(e){return e.reduce((t,{address:r,...n})=>{let i=`${t} ${r}:
24
24
  `;return n.nonce&&(i+=` nonce: ${n.nonce}
25
25
  `),n.balance&&(i+=` balance: ${n.balance}
@@ -31,26 +31,26 @@
31
31
  `)}class rb extends D{constructor(){super(["Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.","Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others."].join(`
32
32
  `),{name:"FeeConflictError"})}}class nb extends D{constructor({v:t}){super(`Invalid \`v\` value "${t}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}}class ib extends D{constructor({transaction:t}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",ns(t),"}","","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 sb extends D{constructor({storageKey:t}){super(`Size for storage key "${t}" is invalid. Expected 32 bytes. Got ${Math.floor((t.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}}class ob extends D{constructor(t,{account:r,docsPath:n,chain:i,data:s,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:f,nonce:u,to:d,value:y}){var g;const p=ns({chain:i&&`${i==null?void 0:i.name} (id: ${i==null?void 0:i.id})`,from:r==null?void 0:r.address,to:d,value:typeof y<"u"&&`${vu(y)} ${((g=i==null?void 0:i.nativeCurrency)==null?void 0:g.symbol)||"ETH"}`,data:s,gas:o,gasPrice:typeof a<"u"&&`${it(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${it(c)} gwei`,maxPriorityFeePerGas:typeof f<"u"&&`${it(f)} gwei`,nonce:u});super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Request Arguments:",p].filter(Boolean),name:"TransactionExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}}class Lp extends D{constructor({blockHash:t,blockNumber:r,blockTag:n,hash:i,index:s}){let o="Transaction";n&&s!==void 0&&(o=`Transaction at block time "${n}" at index "${s}"`),t&&s!==void 0&&(o=`Transaction at block hash "${t}" at index "${s}"`),r&&s!==void 0&&(o=`Transaction at block number "${r}" at index "${s}"`),i&&(o=`Transaction with hash "${i}"`),super(`${o} could not be found.`,{name:"TransactionNotFoundError"})}}class Mp extends D{constructor({hash:t}){super(`Transaction receipt with hash "${t}" could not be found. The Transaction may not be processed on a block yet.`,{name:"TransactionReceiptNotFoundError"})}}class ab extends D{constructor({hash:t}){super(`Timed out while waiting for transaction with hash "${t}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}}const cb=e=>e,so=e=>e;class Dp extends D{constructor(t,{account:r,docsPath:n,chain:i,data:s,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:f,nonce:u,to:d,value:y,stateOverride:p}){var E;const g=r?ke(r):void 0;let b=ns({from:g==null?void 0:g.address,to:d,value:typeof y<"u"&&`${vu(y)} ${((E=i==null?void 0:i.nativeCurrency)==null?void 0:E.symbol)||"ETH"}`,data:s,gas:o,gasPrice:typeof a<"u"&&`${it(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${it(c)} gwei`,maxPriorityFeePerGas:typeof f<"u"&&`${it(f)} gwei`,nonce:u});p&&(b+=`
33
33
  ${tb(p)}`),super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Raw Call Arguments:",b].filter(Boolean),name:"CallExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}}class ub extends D{constructor(t,{abi:r,args:n,contractAddress:i,docsPath:s,functionName:o,sender:a}){const c=sn({abi:r,args:n,name:o}),f=c?Up({abiItem:c,args:n,includeFunctionName:!1,includeName:!1}):void 0,u=c?Tt(c,{includeName:!0}):void 0,d=ns({address:i&&cb(i),function:u,args:f&&f!=="()"&&`${[...Array((o==null?void 0:o.length)??0).keys()].map(()=>" ").join("")}${f}`,sender:a});super(t.shortMessage||`An unknown error occurred while executing the contract function "${o}".`,{cause:t,docsPath:s,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],d&&"Contract Call:",d].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=t,this.contractAddress=i,this.functionName=o,this.sender=a}}class Sc extends D{constructor({abi:t,data:r,functionName:n,message:i}){let s,o,a,c;if(r&&r!=="0x")try{o=$p({abi:t,data:r});const{abiItem:u,errorName:d,args:y}=o;if(d==="Error")c=y[0];else if(d==="Panic"){const[p]=y;c=Rp[p]}else{const p=u?Tt(u,{includeName:!0}):void 0,g=u&&y?Up({abiItem:u,args:y,includeFunctionName:!1,includeName:!1}):void 0;a=[p?`Error: ${p}`:"",g&&g!=="()"?` ${[...Array((d==null?void 0:d.length)??0).keys()].map(()=>" ").join("")}${g}`:""]}}catch(u){s=u}else i&&(c=i);let f;s instanceof dp&&(f=s.signature,a=[`Unable to decode signature "${f}" 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=${f}.`]),super(c&&c!=="execution reverted"||f?[`The contract function "${n}" reverted with the following ${f?"signature":"reason"}:`,c||f].join(`
34
- `):`The contract function "${n}" reverted.`,{cause:s,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=f}}class fb extends D{constructor({functionName:t}){super(`The contract function "${t}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${t}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError"})}}class db extends D{constructor({factory:t}){super(`Deployment for counterfactual contract call failed${t?` for factory "${t}".`:""}`,{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 oo extends D{constructor({data:t,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=t}}class Pn extends D{constructor({body:t,cause:r,details:n,headers:i,status:s,url:o}){super("HTTP request failed.",{cause:r,details:n,metaMessages:[s&&`Status: ${s}`,`URL: ${so(o)}`,t&&`Request body: ${Oe(t)}`].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=t,this.headers=i,this.status=s,this.url=o}}class Eu extends D{constructor({body:t,error:r,url:n}){super("RPC Request failed.",{cause:r,details:r.message,metaMessages:[`URL: ${so(n)}`,`Request body: ${Oe(t)}`],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}),this.code=r.code,this.data=r.data}}class Df extends D{constructor({body:t,url:r}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${so(r)}`,`Request body: ${Oe(t)}`],name:"TimeoutError"})}}const lb=-1;class st extends D{constructor(t,{code:r,docsPath:n,metaMessages:i,name:s,shortMessage:o}){super(o,{cause:t,docsPath:n,metaMessages:i||(t==null?void 0:t.metaMessages),name:s||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=s||t.name,this.code=t instanceof Eu?t.code:r??lb}}class dt extends st{constructor(t,r){super(t,r),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=r.data}}class Ii extends st{constructor(t){super(t,{code:Ii.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(Ii,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class ki extends st{constructor(t){super(t,{code:ki.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(ki,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class Bi extends st{constructor(t,{method:r}={}){super(t,{code:Bi.code,name:"MethodNotFoundRpcError",shortMessage:`The method${r?` "${r}"`:""} does not exist / is not available.`})}}Object.defineProperty(Bi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class Oi extends st{constructor(t){super(t,{code:Oi.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
34
+ `):`The contract function "${n}" reverted.`,{cause:s,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=f}}class fb extends D{constructor({functionName:t}){super(`The contract function "${t}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${t}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError"})}}class db extends D{constructor({factory:t}){super(`Deployment for counterfactual contract call failed${t?` for factory "${t}".`:""}`,{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 oo extends D{constructor({data:t,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=t}}class Pn extends D{constructor({body:t,cause:r,details:n,headers:i,status:s,url:o}){super("HTTP request failed.",{cause:r,details:n,metaMessages:[s&&`Status: ${s}`,`URL: ${so(o)}`,t&&`Request body: ${Oe(t)}`].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=t,this.headers=i,this.status=s,this.url=o}}class Eu extends D{constructor({body:t,error:r,url:n}){super("RPC Request failed.",{cause:r,details:r.message,metaMessages:[`URL: ${so(n)}`,`Request body: ${Oe(t)}`],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}),this.code=r.code,this.data=r.data}}class Df extends D{constructor({body:t,url:r}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${so(r)}`,`Request body: ${Oe(t)}`],name:"TimeoutError"})}}const lb=-1;class st extends D{constructor(t,{code:r,docsPath:n,metaMessages:i,name:s,shortMessage:o}){super(o,{cause:t,docsPath:n,metaMessages:i||(t==null?void 0:t.metaMessages),name:s||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=s||t.name,this.code=t instanceof Eu?t.code:r??lb}}class lt extends st{constructor(t,r){super(t,r),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=r.data}}class Ii extends st{constructor(t){super(t,{code:Ii.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(Ii,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class ki extends st{constructor(t){super(t,{code:ki.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(ki,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class Bi extends st{constructor(t,{method:r}={}){super(t,{code:Bi.code,name:"MethodNotFoundRpcError",shortMessage:`The method${r?` "${r}"`:""} does not exist / is not available.`})}}Object.defineProperty(Bi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class Oi extends st{constructor(t){super(t,{code:Oi.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
35
35
  `)})}}Object.defineProperty(Oi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class Zr extends st{constructor(t){super(t,{code:Zr.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(Zr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class Xr extends st{constructor(t){super(t,{code:Xr.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
36
- `)})}}Object.defineProperty(Xr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class Ci extends st{constructor(t){super(t,{code:Ci.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(Ci,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class Ri extends st{constructor(t){super(t,{code:Ri.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(Ri,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class Ni extends st{constructor(t){super(t,{code:Ni.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(Ni,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class Lr extends st{constructor(t,{method:r}={}){super(t,{code:Lr.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${r?` "${r}"`:""} is not supported.`})}}Object.defineProperty(Lr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class Fn extends st{constructor(t){super(t,{code:Fn.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(Fn,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class Fi extends st{constructor(t){super(t,{code:Fi.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(Fi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class Tn extends dt{constructor(t){super(t,{code:Tn.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(Tn,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class $i extends dt{constructor(t){super(t,{code:$i.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty($i,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class Ui extends dt{constructor(t,{method:r}={}){super(t,{code:Ui.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${r?` " ${r}"`:""}.`})}}Object.defineProperty(Ui,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class Hi extends dt{constructor(t){super(t,{code:Hi.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(Hi,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class Li extends dt{constructor(t){super(t,{code:Li.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(Li,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class Mi extends dt{constructor(t){super(t,{code:Mi.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(Mi,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class $n extends dt{constructor(t){super(t,{code:$n.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty($n,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class Di extends dt{constructor(t){super(t,{code:Di.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(Di,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class ji extends dt{constructor(t){super(t,{code:ji.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(ji,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class zi extends dt{constructor(t){super(t,{code:zi.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(zi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class qi extends dt{constructor(t){super(t,{code:qi.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(qi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class Gi extends dt{constructor(t){super(t,{code:Gi.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(Gi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class Un extends dt{constructor(t){super(t,{code:Un.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(Un,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class pb extends st{constructor(t){super(t,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}const hb=3;function Jr(e,{abi:t,address:r,args:n,docsPath:i,functionName:s,sender:o}){const a=e instanceof oo?e:e instanceof D?e.walk(g=>"data"in g)||e.walk():{},{code:c,data:f,details:u,message:d,shortMessage:y}=a,p=e instanceof Ji?new fb({functionName:s}):[hb,Zr.code].includes(c)&&(f||u||d||y)?new Sc({abi:t,data:typeof f=="object"?f.data:f,functionName:s,message:a instanceof Eu?u:y??d}):e;return new ub(p,{abi:t,args:n,contractAddress:r,docsPath:i,functionName:s,sender:o})}function yb(e){const t=De(`0x${e.substring(4)}`).substring(26);return Qi(`0x${t}`)}async function mb({hash:e,signature:t}){const r=It(e)?e:je(e),{secp256k1:n}=await Promise.resolve().then(()=>mv);return`0x${(()=>{if(typeof t=="object"&&"r"in t&&"s"in t){const{r:f,s:u,v:d,yParity:y}=t,p=Number(y??d),g=jf(p);return new n.Signature(Ue(f),Ue(u)).addRecoveryBit(g)}const o=It(t)?t:je(t);if(Se(o)!==65)throw new Error("invalid signature length");const a=vt(`0x${o.slice(130)}`),c=jf(a);return n.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function jf(e){if(e===0||e===1)return e;if(e===27)return 0;if(e===28)return 1;throw new Error("Invalid yParityOrV value")}async function jp({hash:e,signature:t}){return yb(await mb({hash:e,signature:t}))}function Cr(e,t="hex"){const r=zp(e),n=wu(new Uint8Array(r.length));return r.encode(n),t==="hex"?Ce(n.bytes):n.bytes}function zp(e){return Array.isArray(e)?gb(e.map(t=>zp(t))):bb(e)}function gb(e){const t=e.reduce((i,s)=>i+s.length,0),r=qp(t);return{length:t<=55?1+t:1+r+t,encode(i){t<=55?i.pushByte(192+t):(i.pushByte(247+r),r===1?i.pushUint8(t):r===2?i.pushUint16(t):r===3?i.pushUint24(t):i.pushUint32(t));for(const{encode:s}of e)s(i)}}}function bb(e){const t=typeof e=="string"?kt(e):e,r=qp(t.length);return{length:t.length===1&&t[0]<128?1:t.length<=55?1+t.length:1+r+t.length,encode(i){t.length===1&&t[0]<128?i.pushBytes(t):t.length<=55?(i.pushByte(128+t.length),i.pushBytes(t)):(i.pushByte(183+r),r===1?i.pushUint8(t.length):r===2?i.pushUint16(t.length):r===3?i.pushUint24(t.length):i.pushUint32(t.length),i.pushBytes(t))}}}function qp(e){if(e<2**8)return 1;if(e<2**16)return 2;if(e<2**24)return 3;if(e<2**32)return 4;throw new D("Length is too large.")}function wb(e){const{chainId:t,nonce:r,to:n}=e,i=e.contractAddress??e.address,s=De(Ct(["0x05",Cr([t?K(t):"0x",i,r?K(r):"0x"])]));return n==="bytes"?kt(s):s}async function Gp(e){const{authorization:t,signature:r}=e;return jp({hash:wb(t),signature:r??t})}class vb extends D{constructor(t,{account:r,docsPath:n,chain:i,data:s,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:f,nonce:u,to:d,value:y}){var g;const p=ns({from:r==null?void 0:r.address,to:d,value:typeof y<"u"&&`${vu(y)} ${((g=i==null?void 0:i.nativeCurrency)==null?void 0:g.symbol)||"ETH"}`,data:s,gas:o,gasPrice:typeof a<"u"&&`${it(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${it(c)} gwei`,maxPriorityFeePerGas:typeof f<"u"&&`${it(f)} gwei`,nonce:u});super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Estimate Gas Arguments:",p].filter(Boolean),name:"EstimateGasExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}}class An extends D{constructor({cause:t,message:r}={}){var i;const n=(i=r==null?void 0:r.replace("execution reverted: ",""))==null?void 0:i.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:t,name:"ExecutionRevertedError"})}}Object.defineProperty(An,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(An,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted/});class Qr extends D{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${it(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:t,name:"FeeCapTooHighError"})}}Object.defineProperty(Qr,"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 Pc extends D{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${it(r)}`:""} gwei) cannot be lower than the block base fee.`,{cause:t,name:"FeeCapTooLowError"})}}Object.defineProperty(Pc,"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 Tc extends D{constructor({cause:t,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}is higher than the next one expected.`,{cause:t,name:"NonceTooHighError"})}}Object.defineProperty(Tc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class Ic extends D{constructor({cause:t,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
+ `)})}}Object.defineProperty(Xr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class Ci extends st{constructor(t){super(t,{code:Ci.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(Ci,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class Ri extends st{constructor(t){super(t,{code:Ri.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(Ri,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class Ni extends st{constructor(t){super(t,{code:Ni.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(Ni,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class Lr extends st{constructor(t,{method:r}={}){super(t,{code:Lr.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${r?` "${r}"`:""} is not supported.`})}}Object.defineProperty(Lr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class Fn extends st{constructor(t){super(t,{code:Fn.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(Fn,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class Fi extends st{constructor(t){super(t,{code:Fi.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(Fi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class Tn extends lt{constructor(t){super(t,{code:Tn.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(Tn,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class $i extends lt{constructor(t){super(t,{code:$i.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty($i,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class Ui extends lt{constructor(t,{method:r}={}){super(t,{code:Ui.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${r?` " ${r}"`:""}.`})}}Object.defineProperty(Ui,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class Hi extends lt{constructor(t){super(t,{code:Hi.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(Hi,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class Li extends lt{constructor(t){super(t,{code:Li.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(Li,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class Mi extends lt{constructor(t){super(t,{code:Mi.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(Mi,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class $n extends lt{constructor(t){super(t,{code:$n.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty($n,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class Di extends lt{constructor(t){super(t,{code:Di.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(Di,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class ji extends lt{constructor(t){super(t,{code:ji.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(ji,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class zi extends lt{constructor(t){super(t,{code:zi.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(zi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class qi extends lt{constructor(t){super(t,{code:qi.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(qi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class Gi extends lt{constructor(t){super(t,{code:Gi.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(Gi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class Un extends lt{constructor(t){super(t,{code:Un.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(Un,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class pb extends st{constructor(t){super(t,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}const hb=3;function Jr(e,{abi:t,address:r,args:n,docsPath:i,functionName:s,sender:o}){const a=e instanceof oo?e:e instanceof D?e.walk(g=>"data"in g)||e.walk():{},{code:c,data:f,details:u,message:d,shortMessage:y}=a,p=e instanceof Ji?new fb({functionName:s}):[hb,Zr.code].includes(c)&&(f||u||d||y)?new Sc({abi:t,data:typeof f=="object"?f.data:f,functionName:s,message:a instanceof Eu?u:y??d}):e;return new ub(p,{abi:t,args:n,contractAddress:r,docsPath:i,functionName:s,sender:o})}function yb(e){const t=De(`0x${e.substring(4)}`).substring(26);return Qi(`0x${t}`)}async function mb({hash:e,signature:t}){const r=It(e)?e:je(e),{secp256k1:n}=await Promise.resolve().then(()=>mv);return`0x${(()=>{if(typeof t=="object"&&"r"in t&&"s"in t){const{r:f,s:u,v:d,yParity:y}=t,p=Number(y??d),g=jf(p);return new n.Signature(Ue(f),Ue(u)).addRecoveryBit(g)}const o=It(t)?t:je(t);if(Se(o)!==65)throw new Error("invalid signature length");const a=Et(`0x${o.slice(130)}`),c=jf(a);return n.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function jf(e){if(e===0||e===1)return e;if(e===27)return 0;if(e===28)return 1;throw new Error("Invalid yParityOrV value")}async function jp({hash:e,signature:t}){return yb(await mb({hash:e,signature:t}))}function Cr(e,t="hex"){const r=zp(e),n=wu(new Uint8Array(r.length));return r.encode(n),t==="hex"?Ce(n.bytes):n.bytes}function zp(e){return Array.isArray(e)?gb(e.map(t=>zp(t))):bb(e)}function gb(e){const t=e.reduce((i,s)=>i+s.length,0),r=qp(t);return{length:t<=55?1+t:1+r+t,encode(i){t<=55?i.pushByte(192+t):(i.pushByte(247+r),r===1?i.pushUint8(t):r===2?i.pushUint16(t):r===3?i.pushUint24(t):i.pushUint32(t));for(const{encode:s}of e)s(i)}}}function bb(e){const t=typeof e=="string"?kt(e):e,r=qp(t.length);return{length:t.length===1&&t[0]<128?1:t.length<=55?1+t.length:1+r+t.length,encode(i){t.length===1&&t[0]<128?i.pushBytes(t):t.length<=55?(i.pushByte(128+t.length),i.pushBytes(t)):(i.pushByte(183+r),r===1?i.pushUint8(t.length):r===2?i.pushUint16(t.length):r===3?i.pushUint24(t.length):i.pushUint32(t.length),i.pushBytes(t))}}}function qp(e){if(e<2**8)return 1;if(e<2**16)return 2;if(e<2**24)return 3;if(e<2**32)return 4;throw new D("Length is too large.")}function wb(e){const{chainId:t,nonce:r,to:n}=e,i=e.contractAddress??e.address,s=De(Ct(["0x05",Cr([t?K(t):"0x",i,r?K(r):"0x"])]));return n==="bytes"?kt(s):s}async function Gp(e){const{authorization:t,signature:r}=e;return jp({hash:wb(t),signature:r??t})}class vb extends D{constructor(t,{account:r,docsPath:n,chain:i,data:s,gas:o,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:f,nonce:u,to:d,value:y}){var g;const p=ns({from:r==null?void 0:r.address,to:d,value:typeof y<"u"&&`${vu(y)} ${((g=i==null?void 0:i.nativeCurrency)==null?void 0:g.symbol)||"ETH"}`,data:s,gas:o,gasPrice:typeof a<"u"&&`${it(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${it(c)} gwei`,maxPriorityFeePerGas:typeof f<"u"&&`${it(f)} gwei`,nonce:u});super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Estimate Gas Arguments:",p].filter(Boolean),name:"EstimateGasExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}}class An extends D{constructor({cause:t,message:r}={}){var i;const n=(i=r==null?void 0:r.replace("execution reverted: ",""))==null?void 0:i.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:t,name:"ExecutionRevertedError"})}}Object.defineProperty(An,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(An,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted/});class Qr extends D{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${it(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:t,name:"FeeCapTooHighError"})}}Object.defineProperty(Qr,"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 Pc extends D{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${it(r)}`:""} gwei) cannot be lower than the block base fee.`,{cause:t,name:"FeeCapTooLowError"})}}Object.defineProperty(Pc,"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 Tc extends D{constructor({cause:t,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}is higher than the next one expected.`,{cause:t,name:"NonceTooHighError"})}}Object.defineProperty(Tc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class Ic extends D{constructor({cause:t,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(`
37
37
  `),{cause:t,name:"NonceTooLowError"})}}Object.defineProperty(Ic,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});class kc extends D{constructor({cause:t,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}exceeds the maximum allowed nonce.`,{cause:t,name:"NonceMaxValueError"})}}Object.defineProperty(kc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});class Bc extends D{constructor({cause:t}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(`
38
38
  `),{cause:t,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(Bc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});class Oc extends D{constructor({cause:t,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:t,name:"IntrinsicGasTooHighError"})}}Object.defineProperty(Oc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class Cc extends D{constructor({cause:t,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction is too low.`,{cause:t,name:"IntrinsicGasTooLowError"})}}Object.defineProperty(Cc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class Rc extends D{constructor({cause:t}){super("The transaction type is not supported for this chain.",{cause:t,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty(Rc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});class Vi extends D{constructor({cause:t,maxPriorityFeePerGas:r,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${r?` = ${it(r)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${it(n)} gwei`:""}).`].join(`
39
- `),{cause:t,name:"TipAboveFeeCapError"})}}Object.defineProperty(Vi,"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 is extends D{constructor({cause:t}){super(`An error occurred while executing: ${t==null?void 0:t.shortMessage}`,{cause:t,name:"UnknownNodeError"})}}function ao(e,t){const r=(e.details||"").toLowerCase(),n=e instanceof D?e.walk(i=>(i==null?void 0:i.code)===An.code):e;return n instanceof D?new An({cause:e,message:n.details}):An.nodeMessage.test(r)?new An({cause:e,message:e.details}):Qr.nodeMessage.test(r)?new Qr({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas}):Pc.nodeMessage.test(r)?new Pc({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas}):Tc.nodeMessage.test(r)?new Tc({cause:e,nonce:t==null?void 0:t.nonce}):Ic.nodeMessage.test(r)?new Ic({cause:e,nonce:t==null?void 0:t.nonce}):kc.nodeMessage.test(r)?new kc({cause:e,nonce:t==null?void 0:t.nonce}):Bc.nodeMessage.test(r)?new Bc({cause:e}):Oc.nodeMessage.test(r)?new Oc({cause:e,gas:t==null?void 0:t.gas}):Cc.nodeMessage.test(r)?new Cc({cause:e,gas:t==null?void 0:t.gas}):Rc.nodeMessage.test(r)?new Rc({cause:e}):Vi.nodeMessage.test(r)?new Vi({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas,maxPriorityFeePerGas:t==null?void 0:t.maxPriorityFeePerGas}):new is({cause:e})}function Eb(e,{docsPath:t,...r}){const n=(()=>{const i=ao(e,r);return i instanceof is?e:i})();return new vb(n,{docsPath:t,...r})}function co(e,{format:t}){if(!t)return{};const r={};function n(s){const o=Object.keys(s);for(const a of o)a in e&&(r[a]=e[a]),s[a]&&typeof s[a]=="object"&&!Array.isArray(s[a])&&n(s[a])}const i=t(e||{});return n(i),r}function xu(e,t){return({exclude:r,format:n})=>({exclude:r,format:i=>{const s=t(i);if(r)for(const o of r)delete s[o];return{...s,...n(i)}},type:e})}const xb={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function Yn(e){const t={};return typeof e.authorizationList<"u"&&(t.authorizationList=Ab(e.authorizationList)),typeof e.accessList<"u"&&(t.accessList=e.accessList),typeof e.blobVersionedHashes<"u"&&(t.blobVersionedHashes=e.blobVersionedHashes),typeof e.blobs<"u"&&(typeof e.blobs[0]!="string"?t.blobs=e.blobs.map(r=>Ce(r)):t.blobs=e.blobs),typeof e.data<"u"&&(t.data=e.data),typeof e.from<"u"&&(t.from=e.from),typeof e.gas<"u"&&(t.gas=K(e.gas)),typeof e.gasPrice<"u"&&(t.gasPrice=K(e.gasPrice)),typeof e.maxFeePerBlobGas<"u"&&(t.maxFeePerBlobGas=K(e.maxFeePerBlobGas)),typeof e.maxFeePerGas<"u"&&(t.maxFeePerGas=K(e.maxFeePerGas)),typeof e.maxPriorityFeePerGas<"u"&&(t.maxPriorityFeePerGas=K(e.maxPriorityFeePerGas)),typeof e.nonce<"u"&&(t.nonce=K(e.nonce)),typeof e.to<"u"&&(t.to=e.to),typeof e.type<"u"&&(t.type=xb[e.type]),typeof e.value<"u"&&(t.value=K(e.value)),t}function Ab(e){return e.map(t=>({address:t.address,r:t.r?K(BigInt(t.r)):t.r,s:t.s?K(BigInt(t.s)):t.s,chainId:K(t.chainId),nonce:K(t.nonce),...typeof t.yParity<"u"?{yParity:K(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:K(t.v)}:{}}))}function zf(e){if(!(!e||e.length===0))return e.reduce((t,{slot:r,value:n})=>{if(r.length!==66)throw new If({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new If({size:n.length,targetSize:66,type:"hex"});return t[r]=n,t},{})}function _b(e){const{balance:t,nonce:r,state:n,stateDiff:i,code:s}=e,o={};if(s!==void 0&&(o.code=s),t!==void 0&&(o.balance=K(t)),r!==void 0&&(o.nonce=K(r)),n!==void 0&&(o.state=zf(n)),i!==void 0){if(o.state)throw new eb;o.stateDiff=zf(i)}return o}function Au(e){if(!e)return;const t={};for(const{address:r,...n}of e){if(!Fe(r,{strict:!1}))throw new tt({address:r});if(t[r])throw new Qg({address:r});t[r]=_b(n)}return t}const uo=2n**256n-1n;function on(e){const{account:t,gasPrice:r,maxFeePerGas:n,maxPriorityFeePerGas:i,to:s}=e,o=t?ke(t):void 0;if(o&&!Fe(o.address))throw new tt({address:o.address});if(s&&!Fe(s))throw new tt({address:s});if(typeof r<"u"&&(typeof n<"u"||typeof i<"u"))throw new rb;if(n&&n>uo)throw new Qr({maxFeePerGas:n});if(i&&n&&i>n)throw new Vi({maxFeePerGas:n,maxPriorityFeePerGas:i})}class Sb extends D{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class _u extends D{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class Pb extends D{constructor({maxPriorityFeePerGas:t}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${it(t)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class Vp extends D{constructor({blockHash:t,blockNumber:r}){let n="Block";t&&(n=`Block at hash "${t}"`),r&&(n=`Block at number "${r}"`),super(`${n} could not be found.`,{name:"BlockNotFoundError"})}}const Wp={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function fo(e){const t={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,chainId:e.chainId?vt(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?vt(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?Wp[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};return e.authorizationList&&(t.authorizationList=Ib(e.authorizationList)),t.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof t.v=="bigint"){if(t.v===0n||t.v===27n)return 0;if(t.v===1n||t.v===28n)return 1;if(t.v>=35n)return t.v%2n===0n?1:0}})(),t.type==="legacy"&&(delete t.accessList,delete t.maxFeePerBlobGas,delete t.maxFeePerGas,delete t.maxPriorityFeePerGas,delete t.yParity),t.type==="eip2930"&&(delete t.maxFeePerBlobGas,delete t.maxFeePerGas,delete t.maxPriorityFeePerGas),t.type==="eip1559"&&delete t.maxFeePerBlobGas,t}const Tb=xu("transaction",fo);function Ib(e){return e.map(t=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}function Su(e){const t=(e.transactions??[]).map(r=>typeof r=="string"?r:fo(r));return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:t,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}const kb=xu("block",Su);async function Gt(e,{blockHash:t,blockNumber:r,blockTag:n,includeTransactions:i}={}){var u,d,y;const s=n??"latest",o=i??!1,a=r!==void 0?K(r):void 0;let c=null;if(t?c=await e.request({method:"eth_getBlockByHash",params:[t,o]},{dedupe:!0}):c=await e.request({method:"eth_getBlockByNumber",params:[a||s,o]},{dedupe:!!a}),!c)throw new Vp({blockHash:t,blockNumber:r});return(((y=(d=(u=e.chain)==null?void 0:u.formatters)==null?void 0:d.block)==null?void 0:y.format)||Su)(c)}async function Pu(e){const t=await e.request({method:"eth_gasPrice"});return BigInt(t)}async function Bb(e,t){return Kp(e,t)}async function Kp(e,t){var s,o;const{block:r,chain:n=e.chain,request:i}=t||{};try{const a=((s=n==null?void 0:n.fees)==null?void 0:s.maxPriorityFeePerGas)??((o=n==null?void 0:n.fees)==null?void 0:o.defaultPriorityFee);if(typeof a=="function"){const f=r||await ee(e,Gt,"getBlock")({}),u=await a({block:f,client:e,request:i});if(u===null)throw new Error;return u}if(typeof a<"u")return a;const c=await e.request({method:"eth_maxPriorityFeePerGas"});return Ue(c)}catch{const[a,c]=await Promise.all([r?Promise.resolve(r):ee(e,Gt,"getBlock")({}),ee(e,Pu,"getGasPrice")({})]);if(typeof a.baseFeePerGas!="bigint")throw new _u;const f=c-a.baseFeePerGas;return f<0n?0n:f}}async function Ob(e,t){return Nc(e,t)}async function Nc(e,t){var y,p;const{block:r,chain:n=e.chain,request:i,type:s="eip1559"}=t||{},o=await(async()=>{var g,b;return typeof((g=n==null?void 0:n.fees)==null?void 0:g.baseFeeMultiplier)=="function"?n.fees.baseFeeMultiplier({block:r,client:e,request:i}):((b=n==null?void 0:n.fees)==null?void 0:b.baseFeeMultiplier)??1.2})();if(o<1)throw new Sb;const c=10**(((y=o.toString().split(".")[1])==null?void 0:y.length)??0),f=g=>g*BigInt(Math.ceil(o*c))/BigInt(c),u=r||await ee(e,Gt,"getBlock")({});if(typeof((p=n==null?void 0:n.fees)==null?void 0:p.estimateFeesPerGas)=="function"){const g=await n.fees.estimateFeesPerGas({block:r,client:e,multiply:f,request:i,type:s});if(g!==null)return g}if(s==="eip1559"){if(typeof u.baseFeePerGas!="bigint")throw new _u;const g=typeof(i==null?void 0:i.maxPriorityFeePerGas)=="bigint"?i.maxPriorityFeePerGas:await Kp(e,{block:u,chain:n,request:i}),b=f(u.baseFeePerGas);return{maxFeePerGas:(i==null?void 0:i.maxFeePerGas)??b+g,maxPriorityFeePerGas:g}}return{gasPrice:(i==null?void 0:i.gasPrice)??f(await ee(e,Pu,"getGasPrice")({}))}}async function Tu(e,{address:t,blockTag:r="latest",blockNumber:n}){const i=await e.request({method:"eth_getTransactionCount",params:[t,typeof n=="bigint"?K(n):r]},{dedupe:!!n});return vt(i)}function Iu(e){const{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(s=>kt(s)):e.blobs,i=[];for(const s of n)i.push(Uint8Array.from(t.blobToKzgCommitment(s)));return r==="bytes"?i:i.map(s=>Ce(s))}function ku(e){const{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(o=>kt(o)):e.blobs,i=typeof e.commitments[0]=="string"?e.commitments.map(o=>kt(o)):e.commitments,s=[];for(let o=0;o<n.length;o++){const a=n[o],c=i[o];s.push(Uint8Array.from(t.computeBlobKzgProof(a,c)))}return r==="bytes"?s:s.map(o=>Ce(o))}function Cb(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),c=n?4:0,f=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+f,a,n)}function Rb(e,t,r){return e&t^~e&r}function Nb(e,t,r){return e&t^e&r^t&r}let Yp=class extends pu{constructor(t,r,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(t),this.view=Lo(this.buffer)}update(t){Nn(this),t=eo(t),Bt(t);const{view:r,buffer:n,blockLen:i}=this,s=t.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=Lo(t);for(;i<=s-o;o+=i)this.process(c,o);continue}n.set(t.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Nn(this),wp(t,this),this.finished=!0;const{buffer:r,view:n,blockLen:i,isLE:s}=this;let{pos:o}=this;r[o++]=128,Or(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(n,0),o=0);for(let d=o;d<i;d++)r[d]=0;Cb(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=Lo(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const f=c/4,u=this.get();if(f>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<f;d++)a.setUint32(4*d,u[d],s)}digest(){const{buffer:t,outputLen:r}=this;this.digestInto(t);const n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:r,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return t.destroyed=o,t.finished=s,t.length=i,t.pos=a,i%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}};const mr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),gr=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]),Fb=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]),br=new Uint32Array(64);let Bu=class extends Yp{constructor(t=32){super(64,t,8,!1),this.A=mr[0]|0,this.B=mr[1]|0,this.C=mr[2]|0,this.D=mr[3]|0,this.E=mr[4]|0,this.F=mr[5]|0,this.G=mr[6]|0,this.H=mr[7]|0}get(){const{A:t,B:r,C:n,D:i,E:s,F:o,G:a,H:c}=this;return[t,r,n,i,s,o,a,c]}set(t,r,n,i,s,o,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(t,r){for(let d=0;d<16;d++,r+=4)br[d]=t.getUint32(r,!1);for(let d=16;d<64;d++){const y=br[d-15],p=br[d-2],g=Ft(y,7)^Ft(y,18)^y>>>3,b=Ft(p,17)^Ft(p,19)^p>>>10;br[d]=b+br[d-7]+g+br[d-16]|0}let{A:n,B:i,C:s,D:o,E:a,F:c,G:f,H:u}=this;for(let d=0;d<64;d++){const y=Ft(a,6)^Ft(a,11)^Ft(a,25),p=u+y+Rb(a,c,f)+Fb[d]+br[d]|0,b=(Ft(n,2)^Ft(n,13)^Ft(n,22))+Nb(n,i,s)|0;u=f,f=c,c=a,a=o+p|0,o=s,s=i,i=n,n=p+b|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,u=u+this.H|0,this.set(n,i,s,o,a,c,f,u)}roundClean(){Or(br)}destroy(){this.set(0,0,0,0,0,0,0,0),Or(this.buffer)}},Zp=class extends Bu{constructor(){super(28),this.A=gr[0]|0,this.B=gr[1]|0,this.C=gr[2]|0,this.D=gr[3]|0,this.E=gr[4]|0,this.F=gr[5]|0,this.G=gr[6]|0,this.H=gr[7]|0}};const Xp=to(()=>new Bu),$b=to(()=>new Zp),Ub=Bu,Jp=Xp,Hb=Zp,Lb=$b,Mb=Object.freeze(Object.defineProperty({__proto__:null,SHA224:Hb,SHA256:Ub,sha224:Lb,sha256:Jp},Symbol.toStringTag,{value:"Module"}));function di(e,t){const r=t||"hex",n=Jp(It(e,{strict:!1})?Kn(e):e);return r==="bytes"?n:je(n)}function Db(e){const{commitment:t,version:r=1}=e,n=e.to??(typeof t=="string"?"hex":"bytes"),i=di(t,"bytes");return i.set([r],0),n==="bytes"?i:Ce(i)}function Qp(e){const{commitments:t,version:r}=e,n=e.to??(typeof t[0]=="string"?"hex":"bytes"),i=[];for(const s of t)i.push(Db({commitment:s,to:n,version:r}));return i}const qf=6,eh=32,Ou=4096,th=eh*Ou,Gf=th*qf-1-1*Ou*qf,rh=1;class jb extends D{constructor({maxSize:t,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${t} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}}class nh extends D{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class zb extends D{constructor({hash:t,size:r}){super(`Versioned hash "${t}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}}class qb extends D{constructor({hash:t,version:r}){super(`Versioned hash "${t}" version is invalid.`,{metaMessages:[`Expected: ${rh}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}}function Gb(e){const t=e.to??(typeof e.data=="string"?"hex":"bytes"),r=typeof e.data=="string"?kt(e.data):e.data,n=Se(r);if(!n)throw new nh;if(n>Gf)throw new jb({maxSize:Gf,size:n});const i=[];let s=!0,o=0;for(;s;){const a=wu(new Uint8Array(th));let c=0;for(;c<Ou;){const f=r.slice(o,o+(eh-1));if(a.pushByte(0),a.pushBytes(f),f.length<31){a.pushByte(128),s=!1;break}c++,o+=31}i.push(a)}return t==="bytes"?i.map(a=>a.bytes):i.map(a=>Ce(a.bytes))}function ih(e){const{data:t,kzg:r,to:n}=e,i=e.blobs??Gb({data:t,to:n}),s=e.commitments??Iu({blobs:i,kzg:r,to:n}),o=e.proofs??ku({blobs:i,commitments:s,kzg:r,to:n}),a=[];for(let c=0;c<i.length;c++)a.push({blob:i[c],commitment:s[c],proof:o[c]});return a}function sh(e){if(e.type)return e.type;if(typeof e.authorizationList<"u")return"eip7702";if(typeof e.blobs<"u"||typeof e.blobVersionedHashes<"u"||typeof e.maxFeePerBlobGas<"u"||typeof e.sidecars<"u")return"eip4844";if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")return"eip1559";if(typeof e.gasPrice<"u")return typeof e.accessList<"u"?"eip2930":"legacy";throw new ib({transaction:e})}async function Zn(e){const t=await e.request({method:"eth_chainId"},{dedupe:!0});return vt(t)}const oh=["blobVersionedHashes","chainId","fees","gas","nonce","type"],Vf=new Map;async function lo(e,t){const{account:r=e.account,blobs:n,chain:i,gas:s,kzg:o,nonce:a,nonceManager:c,parameters:f=oh,type:u}=t,d=r&&ke(r),y={...t,...d?{from:d==null?void 0:d.address}:{}};let p;async function g(){return p||(p=await ee(e,Gt,"getBlock")({blockTag:"latest"}),p)}let b;async function E(){return b||(i?i.id:typeof t.chainId<"u"?t.chainId:(b=await ee(e,Zn,"getChainId")({}),b))}if(f.includes("nonce")&&typeof a>"u"&&d)if(c){const A=await E();y.nonce=await c.consume({address:d.address,chainId:A,client:e})}else y.nonce=await ee(e,Tu,"getTransactionCount")({address:d.address,blockTag:"pending"});if((f.includes("blobVersionedHashes")||f.includes("sidecars"))&&n&&o){const A=Iu({blobs:n,kzg:o});if(f.includes("blobVersionedHashes")){const P=Qp({commitments:A,to:"hex"});y.blobVersionedHashes=P}if(f.includes("sidecars")){const P=ku({blobs:n,commitments:A,kzg:o}),w=ih({blobs:n,commitments:A,proofs:P,to:"hex"});y.sidecars=w}}if(f.includes("chainId")&&(y.chainId=await E()),(f.includes("fees")||f.includes("type"))&&typeof u>"u")try{y.type=sh(y)}catch{let A=Vf.get(e.uid);if(typeof A>"u"){const P=await g();A=typeof(P==null?void 0:P.baseFeePerGas)=="bigint",Vf.set(e.uid,A)}y.type=A?"eip1559":"legacy"}if(f.includes("fees"))if(y.type!=="legacy"&&y.type!=="eip2930"){if(typeof y.maxFeePerGas>"u"||typeof y.maxPriorityFeePerGas>"u"){const A=await g(),{maxFeePerGas:P,maxPriorityFeePerGas:w}=await Nc(e,{block:A,chain:i,request:y});if(typeof t.maxPriorityFeePerGas>"u"&&t.maxFeePerGas&&t.maxFeePerGas<w)throw new Pb({maxPriorityFeePerGas:w});y.maxPriorityFeePerGas=w,y.maxFeePerGas=P}}else{if(typeof t.maxFeePerGas<"u"||typeof t.maxPriorityFeePerGas<"u")throw new _u;if(typeof t.gasPrice>"u"){const A=await g(),{gasPrice:P}=await Nc(e,{block:A,chain:i,request:y,type:"legacy"});y.gasPrice=P}}return f.includes("gas")&&typeof s>"u"&&(y.gas=await ee(e,Cu,"estimateGas")({...y,account:d&&{address:d.address,type:"json-rpc"}})),on(y),delete y.parameters,y}async function ah(e,{address:t,blockNumber:r,blockTag:n="latest"}){const i=typeof r=="bigint"?K(r):void 0,s=await e.request({method:"eth_getBalance",params:[t,i||n]});return BigInt(s)}async function Cu(e,t){var i,s,o;const{account:r=e.account}=t,n=r?ke(r):void 0;try{let V=function(X){const{block:J,request:M,rpcStateOverride:B}=X;return e.request({method:"eth_estimateGas",params:B?[M,J??"latest",B]:J?[M,J]:[M]})};const{accessList:a,authorizationList:c,blobs:f,blobVersionedHashes:u,blockNumber:d,blockTag:y,data:p,gas:g,gasPrice:b,maxFeePerBlobGas:E,maxFeePerGas:A,maxPriorityFeePerGas:P,nonce:w,value:_,stateOverride:T,...I}=await lo(e,{...t,parameters:(n==null?void 0:n.type)==="local"?void 0:["blobVersionedHashes"]}),L=(typeof d=="bigint"?K(d):void 0)||y,S=Au(T),$=await(async()=>{if(I.to)return I.to;if(c&&c.length>0)return await Gp({authorization:c[0]}).catch(()=>{throw new D("`to` is required. Could not infer from `authorizationList`")})})();on(t);const C=(o=(s=(i=e.chain)==null?void 0:i.formatters)==null?void 0:s.transactionRequest)==null?void 0:o.format,j=(C||Yn)({...co(I,{format:C}),from:n==null?void 0:n.address,accessList:a,authorizationList:c,blobs:f,blobVersionedHashes:u,data:p,gas:g,gasPrice:b,maxFeePerBlobGas:E,maxFeePerGas:A,maxPriorityFeePerGas:P,nonce:w,to:$,value:_});let Y=BigInt(await V({block:L,request:j,rpcStateOverride:S}));if(c){const X=await ah(e,{address:j.from}),J=await Promise.all(c.map(async M=>{const{address:B}=M,q=await V({block:L,request:{authorizationList:void 0,data:p,from:n==null?void 0:n.address,to:B,value:K(X)},rpcStateOverride:S}).catch(()=>100000n);return 2n*BigInt(q)}));Y+=J.reduce((M,B)=>M+B,0n)}return Y}catch(a){throw Eb(a,{...t,account:n,chain:e.chain})}}async function ch(e,t){const{abi:r,address:n,args:i,functionName:s,dataSuffix:o,...a}=t,c=xt({abi:r,args:i,functionName:s});try{return await ee(e,Cu,"estimateGas")({data:`${c}${o?o.replace("0x",""):""}`,to:n,...a})}catch(f){const u=a.account?ke(a.account):void 0;throw Jr(f,{abi:r,address:n,args:i,docsPath:"/docs/contract/estimateContractGas",functionName:s,sender:u==null?void 0:u.address})}}function ss(e,t){if(!Fe(e,{strict:!1}))throw new tt({address:e});if(!Fe(t,{strict:!1}))throw new tt({address:t});return e.toLowerCase()===t.toLowerCase()}const Wf="/docs/contract/decodeEventLog";function Ru(e){const{abi:t,data:r,strict:n,topics:i}=e,s=n??!0,[o,...a]=i;if(!o)throw new Fm({docsPath:Wf});const c=t.find(b=>b.type==="event"&&o===ro(Tt(b)));if(!(c&&"name"in c)||c.type!=="event")throw new lp(o,{docsPath:Wf});const{name:f,inputs:u}=c,d=u==null?void 0:u.some(b=>!("name"in b&&b.name)),y=d?[]:{},p=u.map((b,E)=>[b,E]).filter(([b])=>"indexed"in b&&b.indexed);for(let b=0;b<p.length;b++){const[E,A]=p[b],P=a[b];if(!P)throw new Qs({abiItem:c,param:E});y[d?A:E.name||A]=Vb({param:E,value:P})}const g=u.filter(b=>!("indexed"in b&&b.indexed));if(g.length>0){if(r&&r!=="0x")try{const b=rs(g,r);if(b)if(d)for(let E=0;E<u.length;E++)y[E]=y[E]??b.shift();else for(let E=0;E<g.length;E++)y[g[E].name]=b[E]}catch(b){if(s)throw b instanceof fp||b instanceof Fp?new _i({abiItem:c,data:r,params:g,size:Se(r)}):b}else if(s)throw new _i({abiItem:c,data:"0x",params:g,size:0})}return{eventName:f,args:Object.values(y).length>0?y:void 0}}function Vb({param:e,value:t}){return e.type==="string"||e.type==="bytes"||e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/)?t:(rs([e],t)||[])[0]}function Nu(e){const{abi:t,args:r,logs:n,strict:i=!0}=e,s=(()=>{if(e.eventName)return Array.isArray(e.eventName)?e.eventName:[e.eventName]})();return n.map(o=>{var a;try{const c=t.find(u=>u.type==="event"&&o.topics[0]===ro(u));if(!c)return null;const f=Ru({...o,abi:[c],strict:i});return s&&!s.includes(f.eventName)||!Wb({args:f.args,inputs:c.inputs,matchArgs:r})?null:{...f,...o}}catch(c){let f,u;if(c instanceof lp)return null;if(c instanceof _i||c instanceof Qs){if(i)return null;f=c.abiItem.name,u=(a=c.abiItem.inputs)==null?void 0:a.some(d=>!("name"in d&&d.name))}return{...o,args:u?[]:{},eventName:f}}}).filter(Boolean)}function Wb(e){const{args:t,inputs:r,matchArgs:n}=e;if(!n)return!0;if(!t)return!1;function i(s,o,a){try{return s.type==="address"?ss(o,a):s.type==="string"||s.type==="bytes"?De(Kn(o))===a:o===a}catch{return!1}}return Array.isArray(t)&&Array.isArray(n)?n.every((s,o)=>{if(s==null)return!0;const a=r[o];return a?(Array.isArray(s)?s:[s]).some(f=>i(a,f,t[o])):!1}):typeof t=="object"&&!Array.isArray(t)&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).every(([s,o])=>{if(o==null)return!0;const a=r.find(f=>f.name===s);return a?(Array.isArray(o)?o:[o]).some(f=>i(a,f,t[s])):!1}):!1}function cr(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}async function Fu(e,{address:t,blockHash:r,fromBlock:n,toBlock:i,event:s,events:o,args:a,strict:c}={}){const f=c??!1,u=o??(s?[s]:void 0);let d=[];u&&(d=[u.flatMap(b=>ts({abi:[b],eventName:b.name,args:o?void 0:a}))],s&&(d=d[0]));let y;r?y=await e.request({method:"eth_getLogs",params:[{address:t,topics:d,blockHash:r}]}):y=await e.request({method:"eth_getLogs",params:[{address:t,topics:d,fromBlock:typeof n=="bigint"?K(n):n,toBlock:typeof i=="bigint"?K(i):i}]});const p=y.map(g=>cr(g));return u?Nu({abi:u,args:a,logs:p,strict:f}):p}async function $u(e,t){const{abi:r,address:n,args:i,blockHash:s,eventName:o,fromBlock:a,toBlock:c,strict:f}=t,u=o?sn({abi:r,name:o}):void 0,d=u?void 0:r.filter(y=>y.type==="event");return ee(e,Fu,"getLogs")({address:n,args:i,blockHash:s,event:u,events:d,fromBlock:a,toBlock:c,strict:f})}const jo="/docs/contract/decodeFunctionResult";function an(e){const{abi:t,args:r,functionName:n,data:i}=e;let s=t[0];if(n){const a=sn({abi:t,args:r,name:n});if(!a)throw new Cn(n,{docsPath:jo});s=a}if(s.type!=="function")throw new Cn(void 0,{docsPath:jo});if(!s.outputs)throw new pp(s.name,{docsPath:jo});const o=rs(s.outputs,i);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 Uu=BigInt(0),Fc=BigInt(1);function Ws(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function gs(e){const t=e.toString(16);return t.length&1?"0"+t:t}function uh(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?Uu:BigInt("0x"+e)}function po(e){return uh(Pi(e))}function fh(e){return Bt(e),uh(Pi(Uint8Array.from(e).reverse()))}function Hu(e,t){return lu(e.toString(16).padStart(t*2,"0"))}function dh(e,t){return Hu(e,t).reverse()}function yt(e,t,r){let n;if(typeof t=="string")try{n=lu(t)}catch(s){throw new Error(e+" must be hex string or Uint8Array, cause: "+s)}else if(du(t))n=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");const i=n.length;if(typeof r=="number"&&i!==r)throw new Error(e+" of length "+r+" expected, got "+i);return n}const zo=e=>typeof e=="bigint"&&Uu<=e;function Kb(e,t,r){return zo(e)&&zo(t)&&zo(r)&&t<=e&&e<r}function Yb(e,t,r,n){if(!Kb(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function Zb(e){let t;for(t=0;e>Uu;e>>=Fc,t+=1);return t}const ho=e=>(Fc<<BigInt(e))-Fc;function Xb(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");const n=p=>new Uint8Array(p),i=p=>Uint8Array.of(p);let s=n(e),o=n(e),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},f=(...p)=>r(o,s,...p),u=(p=n(0))=>{o=f(i(0),p),s=f(),p.length!==0&&(o=f(i(1),p),s=f())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let p=0;const g=[];for(;p<t;){s=f();const b=s.slice();g.push(b),p+=s.length}return Hr(...g)};return(p,g)=>{c(),u(p);let b;for(;!(b=g(d()));)u();return c(),b}}function Lu(e,t,r={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function n(i,s,o){const a=e[i];if(o&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${c}`)}Object.entries(t).forEach(([i,s])=>n(i,s,!1)),Object.entries(r).forEach(([i,s])=>n(i,s,!0))}function Kf(e){const t=new WeakMap;return(r,...n)=>{const i=t.get(r);if(i!==void 0)return i;const s=e(r,...n);return t.set(r,s),s}}const Jb="0.1.1";function Qb(){return Jb}class xe extends Error{constructor(t,r={}){const n=(()=>{var c;if(r.cause instanceof xe){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:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),i=r.cause instanceof xe&&r.cause.docsPath||r.docsPath,o=`https://oxlib.sh${i??""}`,a=[t||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||i?["",n?`Details: ${n}`:void 0,i?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
40
- `);super(a,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,"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,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${Qb()}`}),this.cause=r.cause,this.details=n,this.docs=o,this.docsPath=i,this.shortMessage=t}walk(t){return lh(this,t)}}function lh(e,t){return t!=null&&t(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause?lh(e.cause,t):t?null:e}const ew="#__bigint";function tw(e,t,r){return JSON.stringify(e,(n,i)=>typeof i=="bigint"?i.toString()+ew:i,r)}function rw(e,t){if(Zf(e)>t)throw new lw({givenSize:Zf(e),maxSize:t})}const Xt={zero:48,nine:57,A:65,F:70,a:97,f:102};function Yf(e){if(e>=Xt.zero&&e<=Xt.nine)return e-Xt.zero;if(e>=Xt.A&&e<=Xt.F)return e-(Xt.A-10);if(e>=Xt.a&&e<=Xt.f)return e-(Xt.a-10)}function nw(e,t={}){const{dir:r,size:n=32}=t;if(n===0)return e;if(e.length>n)throw new pw({size:e.length,targetSize:n,type:"Bytes"});const i=new Uint8Array(n);for(let s=0;s<n;s++){const o=r==="right";i[o?s:n-s-1]=e[o?s:e.length-s-1]}return i}function Mu(e,t){if(Et(e)>t)throw new bw({givenSize:Et(e),maxSize:t})}function iw(e,t){if(typeof t=="number"&&t>0&&t>Et(e)-1)throw new gh({offset:t,position:"start",size:Et(e)})}function sw(e,t,r){if(typeof t=="number"&&typeof r=="number"&&Et(e)!==r-t)throw new gh({offset:r,position:"end",size:Et(e)})}function ph(e,t={}){const{dir:r,size:n=32}=t;if(n===0)return e;const i=e.replace("0x","");if(i.length>n*2)throw new ww({size:Math.ceil(i.length/2),targetSize:n,type:"Hex"});return`0x${i[r==="right"?"padEnd":"padStart"](n*2,"0")}`}const ow=new TextEncoder;function aw(e){return e instanceof Uint8Array?e:typeof e=="string"?uw(e):cw(e)}function cw(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function uw(e,t={}){const{size:r}=t;let n=e;r&&(Mu(e,r),n=tn(e,r));let i=n.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,o=new Uint8Array(s);for(let a=0,c=0;a<s;a++){const f=Yf(i.charCodeAt(c++)),u=Yf(i.charCodeAt(c++));if(f===void 0||u===void 0)throw new xe(`Invalid byte sequence ("${i[c-2]}${i[c-1]}" in "${i}").`);o[a]=f*16+u}return o}function fw(e,t={}){const{size:r}=t,n=ow.encode(e);return typeof r=="number"?(rw(n,r),dw(n,r)):n}function dw(e,t){return nw(e,{dir:"right",size:t})}function Zf(e){return e.length}let lw=class extends xe{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}},pw=class extends xe{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}};const hw=new TextEncoder,yw=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function mw(e,t={}){const{strict:r=!1}=t;if(!e)throw new Xf(e);if(typeof e!="string")throw new Xf(e);if(r&&!/^0x[0-9a-fA-F]*$/.test(e))throw new Jf(e);if(!e.startsWith("0x"))throw new Jf(e)}function Vt(...e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function hh(e,t={}){const r=`0x${Number(e)}`;return typeof t.size=="number"?(Mu(r,t.size),en(r,t.size)):r}function yh(e,t={}){let r="";for(let i=0;i<e.length;i++)r+=yw[e[i]];const n=`0x${r}`;return typeof t.size=="number"?(Mu(n,t.size),tn(n,t.size)):n}function Je(e,t={}){const{signed:r,size:n}=t,i=BigInt(e);let s;n?r?s=(1n<<BigInt(n)*8n-1n)-1n:s=2n**(BigInt(n)*8n)-1n:typeof e=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&r?-s-1n:0;if(s&&i>s||i<o){const f=typeof e=="bigint"?"n":"";throw new mh({max:s?`${s}${f}`:void 0,min:`${o}${f}`,signed:r,size:n,value:`${e}${f}`})}const c=`0x${(r&&i<0?(1n<<BigInt(n*8))+BigInt(i):i).toString(16)}`;return n?en(c,n):c}function Du(e,t={}){return yh(hw.encode(e),t)}function en(e,t){return ph(e,{dir:"left",size:t})}function tn(e,t){return ph(e,{dir:"right",size:t})}function ju(e,t,r,n={}){const{strict:i}=n;iw(e,t);const s=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;return i&&sw(s,t,r),s}function Et(e){return Math.ceil((e.length-2)/2)}function gw(e,t={}){const{strict:r=!1}=t;try{return mw(e,{strict:r}),!0}catch{return!1}}class mh extends xe{constructor({max:t,min:r,signed:n,size:i,value:s}){super(`Number \`${s}\` is not in safe${i?` ${i*8}-bit`:""}${n?" signed":" unsigned"} integer range ${t?`(\`${r}\` to \`${t}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class Xf extends xe{constructor(t){super(`Value \`${typeof t=="object"?tw(t):t}\` of type \`${typeof t}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class Jf extends xe{constructor(t){super(`Value \`${t}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}class bw extends xe{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}}class gh extends xe{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${t}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}class ww extends xe{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}function vw(e){return{address:e.address,amount:Je(e.amount),index:Je(e.index),validatorIndex:Je(e.validatorIndex)}}function bh(e){return{...typeof e.baseFeePerGas=="bigint"&&{baseFeePerGas:Je(e.baseFeePerGas)},...typeof e.blobBaseFee=="bigint"&&{blobBaseFee:Je(e.blobBaseFee)},...typeof e.feeRecipient=="string"&&{feeRecipient:e.feeRecipient},...typeof e.gasLimit=="bigint"&&{gasLimit:Je(e.gasLimit)},...typeof e.number=="bigint"&&{number:Je(e.number)},...typeof e.prevRandao=="bigint"&&{prevRandao:Je(e.prevRandao)},...typeof e.time=="bigint"&&{time:Je(e.time)},...e.withdrawals&&{withdrawals:e.withdrawals.map(vw)}}}const $c=[{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"}],Uc=[{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"}]}],wh=[{inputs:[],name:"ResolverNotFound",type:"error"},{inputs:[],name:"ResolverWildcardNotSupported",type:"error"},{inputs:[],name:"ResolverNotContract",type:"error"},{inputs:[{name:"returnData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{components:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"errors",type:"tuple[]"}],name:"HttpError",type:"error"}],vh=[...wh,{name:"resolve",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]},{name:"resolve",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"}]}],Ew=[...wh,{name:"reverse",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolvedAddress"},{type:"address",name:"reverseResolver"},{type:"address",name:"resolver"}]},{name:"reverse",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolvedAddress"},{type:"address",name:"reverseResolver"},{type:"address",name:"resolver"}]}],Qf=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],ed=[{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"}]}],td=[{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"}],xw="0x82ad56cb",Eh="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",Aw="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",_w="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572";class Hc extends D{constructor({blockNumber:t,chain:r,contract:n}){super(`Chain "${r.name}" does not support contract "${n.name}".`,{metaMessages:["This could be due to any of the following:",...t&&n.blockCreated&&n.blockCreated>t?[`- The contract "${n.name}" was not deployed until block ${n.blockCreated} (current block ${t}).`]:[`- The chain does not have the contract "${n.name}" configured.`]],name:"ChainDoesNotSupportContract"})}}class Sw extends D{constructor({chain:t,currentChainId:r}){super(`The current chain of the wallet (id: ${r}) does not match the target chain for the transaction (id: ${t.id} – ${t.name}).`,{metaMessages:[`Current Chain ID: ${r}`,`Expected Chain ID: ${t.id} – ${t.name}`],name:"ChainMismatchError"})}}class Pw extends D{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(`
41
- `),{name:"ChainNotFoundError"})}}class xh extends D{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}class yo extends D{constructor({chainId:t}){super(typeof t=="number"?`Chain ID "${t}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}const qo="/docs/contract/encodeDeployData";function mo(e){const{abi:t,args:r,bytecode:n}=e;if(!r||r.length===0)return n;const i=t.find(o=>"type"in o&&o.type==="constructor");if(!i)throw new Bm({docsPath:qo});if(!("inputs"in i))throw new Sf({docsPath:qo});if(!i.inputs||i.inputs.length===0)throw new Sf({docsPath:qo});const s=pr(i.inputs,r);return Ct([n,s])}function Xn({blockNumber:e,chain:t,contract:r}){var i;const n=(i=t==null?void 0:t.contracts)==null?void 0:i[r];if(!n)throw new Hc({chain:t,contract:{name:r}});if(e&&n.blockCreated&&n.blockCreated>e)throw new Hc({blockNumber:e,chain:t,contract:{name:r,blockCreated:n.blockCreated}});return n.address}function Ah(e,{docsPath:t,...r}){const n=(()=>{const i=ao(e,r);return i instanceof is?e:i})();return new Dp(n,{docsPath:t,...r})}function zu(){let e=()=>{},t=()=>{};return{promise:new Promise((n,i)=>{e=n,t=i}),resolve:e,reject:t}}const Go=new Map;function _h({fn:e,id:t,shouldSplitBatch:r,wait:n=0,sort:i}){const s=async()=>{const u=c();o();const d=u.map(({args:y})=>y);d.length!==0&&e(d).then(y=>{i&&Array.isArray(y)&&y.sort(i);for(let p=0;p<u.length;p++){const{resolve:g}=u[p];g==null||g([y[p],y])}}).catch(y=>{for(let p=0;p<u.length;p++){const{reject:g}=u[p];g==null||g(y)}})},o=()=>Go.delete(t),a=()=>c().map(({args:u})=>u),c=()=>Go.get(t)||[],f=u=>Go.set(t,[...c(),u]);return{flush:o,async schedule(u){const{promise:d,resolve:y,reject:p}=zu();return(r==null?void 0:r([...a(),u]))&&s(),c().length>0?(f({args:u,resolve:y,reject:p}),d):(f({args:u,resolve:y,reject:p}),setTimeout(s,n),d)}}}async function os(e,t){var j,V,Y,X;const{account:r=e.account,authorizationList:n,batch:i=!!((j=e.batch)!=null&&j.multicall),blockNumber:s,blockTag:o="latest",accessList:a,blobs:c,blockOverrides:f,code:u,data:d,factory:y,factoryData:p,gas:g,gasPrice:b,maxFeePerBlobGas:E,maxFeePerGas:A,maxPriorityFeePerGas:P,nonce:w,to:_,value:T,stateOverride:I,...R}=t,L=r?ke(r):void 0;if(u&&(y||p))throw new D("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(u&&_)throw new D("Cannot provide both `code` & `to` as parameters.");const S=u&&d,$=y&&p&&_&&d,C=S||$,U=S?kw({code:u,data:d}):$?Bw({data:d,factory:y,factoryData:p,to:_}):d;try{on(t);const M=(typeof s=="bigint"?K(s):void 0)||o,B=f?bh(f):void 0,q=Au(I),W=(X=(Y=(V=e.chain)==null?void 0:V.formatters)==null?void 0:Y.transactionRequest)==null?void 0:X.format,N=(W||Yn)({...co(R,{format:W}),from:L==null?void 0:L.address,accessList:a,authorizationList:n,blobs:c,data:U,gas:g,gasPrice:b,maxFeePerBlobGas:E,maxFeePerGas:A,maxPriorityFeePerGas:P,nonce:w,to:C?void 0:_,value:T});if(i&&Tw({request:N})&&!q&&!B)try{return await Iw(e,{...N,blockNumber:s,blockTag:o})}catch(Q){if(!(Q instanceof xh)&&!(Q instanceof Hc))throw Q}const H=(()=>{const Q=[N,M];return q&&B?[...Q,q,B]:q?[...Q,q]:B?[...Q,{},B]:Q})(),Z=await e.request({method:"eth_call",params:H});return Z==="0x"?{data:void 0}:{data:Z}}catch(J){const M=Ow(J),{offchainLookup:B,offchainLookupSignature:q}=await Promise.resolve().then(()=>require("./ccip-PvTvY3At.cjs"));if(e.ccipRead!==!1&&(M==null?void 0:M.slice(0,10))===q&&_)return{data:await B(e,{data:M,to:_})};throw C&&(M==null?void 0:M.slice(0,10))==="0x101bb98d"?new db({factory:y}):Ah(J,{...t,account:L,chain:e.chain})}}function Tw({request:e}){const{data:t,to:r,...n}=e;return!(!t||t.startsWith(xw)||!r||Object.values(n).filter(i=>typeof i<"u").length>0)}async function Iw(e,t){var b;const{batchSize:r=1024,wait:n=0}=typeof((b=e.batch)==null?void 0:b.multicall)=="object"?e.batch.multicall:{},{blockNumber:i,blockTag:s="latest",data:o,multicallAddress:a,to:c}=t;let f=a;if(!f){if(!e.chain)throw new xh;f=Xn({blockNumber:i,chain:e.chain,contract:"multicall3"})}const d=(typeof i=="bigint"?K(i):void 0)||s,{schedule:y}=_h({id:`${e.uid}.${d}`,wait:n,shouldSplitBatch(E){return E.reduce((P,{data:w})=>P+(w.length-2),0)>r*2},fn:async E=>{const A=E.map(_=>({allowFailure:!0,callData:_.data,target:_.to})),P=xt({abi:$c,args:[A],functionName:"aggregate3"}),w=await e.request({method:"eth_call",params:[{data:P,to:f},d]});return an({abi:$c,args:[A],functionName:"aggregate3",data:w||"0x"})}}),[{returnData:p,success:g}]=await y({data:o,to:c});if(!g)throw new oo({data:p});return p==="0x"?{data:void 0}:{data:p}}function kw(e){const{code:t,data:r}=e;return mo({abi:ap(["constructor(bytes, bytes)"]),bytecode:Eh,args:[t,r]})}function Bw(e){const{data:t,factory:r,factoryData:n,to:i}=e;return mo({abi:ap(["constructor(address, bytes, address, bytes)"]),bytecode:Aw,args:[i,t,r,n]})}function Ow(e){var r;if(!(e instanceof D))return;const t=e.walk();return typeof(t==null?void 0:t.data)=="object"?(r=t.data)==null?void 0:r.data:t.data}async function Wt(e,t){const{abi:r,address:n,args:i,functionName:s,...o}=t,a=xt({abi:r,args:i,functionName:s});try{const{data:c}=await ee(e,os,"call")({...o,data:a,to:n});return an({abi:r,args:i,functionName:s,data:c||"0x"})}catch(c){throw Jr(c,{abi:r,address:n,args:i,docsPath:"/docs/contract/readContract",functionName:s})}}async function Sh(e,t){const{abi:r,address:n,args:i,dataSuffix:s,functionName:o,...a}=t,c=a.account?ke(a.account):e.account,f=xt({abi:r,args:i,functionName:o});try{const{data:u}=await ee(e,os,"call")({batch:!1,data:`${f}${s?s.replace("0x",""):""}`,to:n,...a,account:c}),d=an({abi:r,args:i,functionName:o,data:u||"0x"}),y=r.filter(p=>"name"in p&&p.name===t.functionName);return{result:d,request:{abi:y,address:n,args:i,dataSuffix:s,functionName:o,...a,account:c}}}catch(u){throw Jr(u,{abi:r,address:n,args:i,docsPath:"/docs/contract/simulateContract",functionName:o,sender:c==null?void 0:c.address})}}const Vo=new Map,rd=new Map;let Cw=0;function ur(e,t,r){const n=++Cw,i=()=>Vo.get(e)||[],s=()=>{const u=i();Vo.set(e,u.filter(d=>d.id!==n))},o=()=>{const u=i();if(!u.some(y=>y.id===n))return;const d=rd.get(e);if(u.length===1&&d){const y=d();y instanceof Promise&&y.catch(()=>{})}s()},a=i();if(Vo.set(e,[...a,{id:n,fns:t}]),a&&a.length>0)return o;const c={};for(const u in t)c[u]=(...d)=>{var p,g;const y=i();if(y.length!==0)for(const b of y)(g=(p=b.fns)[u])==null||g.call(p,...d)};const f=r(c);return typeof f=="function"&&rd.set(e,f),o}async function Lc(e){return new Promise(t=>setTimeout(t,e))}function Jn(e,{emitOnBegin:t,initialWaitTime:r,interval:n}){let i=!0;const s=()=>i=!1;return(async()=>{let a;t&&(a=await e({unpoll:s}));const c=await(r==null?void 0:r(a))??n;await Lc(c);const f=async()=>{i&&(await e({unpoll:s}),await Lc(n),f())};f()})(),s}const Rw=new Map,Nw=new Map;function Fw(e){const t=(i,s)=>({clear:()=>s.delete(i),get:()=>s.get(i),set:o=>s.set(i,o)}),r=t(e,Rw),n=t(e,Nw);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function $w(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){const n=Fw(t),i=n.response.get();if(i&&r>0&&new Date().getTime()-i.created.getTime()<r)return i.data;let s=n.promise.get();s||(s=e(),n.promise.set(s));try{const o=await s;return n.response.set({created:new Date,data:o}),o}finally{n.promise.clear()}}const Uw=e=>`blockNumber.${e}`;async function as(e,{cacheTime:t=e.cacheTime}={}){const r=await $w(()=>e.request({method:"eth_blockNumber"}),{cacheKey:Uw(e.uid),cacheTime:t});return BigInt(r)}async function go(e,{filter:t}){const r="strict"in t&&t.strict,n=await t.request({method:"eth_getFilterChanges",params:[t.id]});if(typeof n[0]=="string")return n;const i=n.map(s=>cr(s));return!("abi"in t)||!t.abi?i:Nu({abi:t.abi,logs:i,strict:r})}async function bo(e,{filter:t}){return t.request({method:"eth_uninstallFilter",params:[t.id]})}function Ph(e,t){const{abi:r,address:n,args:i,batch:s=!0,eventName:o,fromBlock:a,onError:c,onLogs:f,poll:u,pollingInterval:d=e.pollingInterval,strict:y}=t;return(typeof u<"u"?u:typeof a=="bigint"?!0:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")))?(()=>{const E=y??!1,A=Oe(["watchContractEvent",n,i,s,e.uid,o,d,E,a]);return ur(A,{onLogs:f,onError:c},P=>{let w;a!==void 0&&(w=a-1n);let _,T=!1;const I=Jn(async()=>{var R;if(!T){try{_=await ee(e,bu,"createContractEventFilter")({abi:r,address:n,args:i,eventName:o,strict:E,fromBlock:a})}catch{}T=!0;return}try{let L;if(_)L=await ee(e,go,"getFilterChanges")({filter:_});else{const S=await ee(e,as,"getBlockNumber")({});w&&w<S?L=await ee(e,$u,"getContractEvents")({abi:r,address:n,args:i,eventName:o,fromBlock:w+1n,toBlock:S,strict:E}):L=[],w=S}if(L.length===0)return;if(s)P.onLogs(L);else for(const S of L)P.onLogs([S])}catch(L){_&&L instanceof Xr&&(T=!1),(R=P.onError)==null||R.call(P,L)}},{emitOnBegin:!0,interval:d});return async()=>{_&&await ee(e,bo,"uninstallFilter")({filter:_}),I()}})})():(()=>{const E=y??!1,A=Oe(["watchContractEvent",n,i,s,e.uid,o,d,E]);let P=!0,w=()=>P=!1;return ur(A,{onLogs:f,onError:c},_=>((async()=>{try{const T=(()=>{if(e.transport.type==="fallback"){const L=e.transport.transports.find(S=>S.config.type==="webSocket"||S.config.type==="ipc");return L?L.value:e.transport}return e.transport})(),I=o?ts({abi:r,eventName:o,args:i}):[],{unsubscribe:R}=await T.subscribe({params:["logs",{address:n,topics:I}],onData(L){var $;if(!P)return;const S=L.result;try{const{eventName:C,args:U}=Ru({abi:r,data:S.data,topics:S.topics,strict:y}),j=cr(S,{args:U,eventName:C});_.onLogs([j])}catch(C){let U,j;if(C instanceof _i||C instanceof Qs){if(y)return;U=C.abiItem.name,j=($=C.abiItem.inputs)==null?void 0:$.some(Y=>!("name"in Y&&Y.name))}const V=cr(S,{args:j?[]:{},eventName:U});_.onLogs([V])}},onError(L){var S;(S=_.onError)==null||S.call(_,L)}});w=R,P||w()}catch(T){c==null||c(T)}})(),()=>w()))})()}class cn extends D{constructor({docsPath:t}={}){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(`
42
- `),{docsPath:t,docsSlug:"account",name:"AccountNotFoundError"})}}class $s extends D{constructor({docsPath:t,metaMessages:r,type:n}){super(`Account type "${n}" is not supported.`,{docsPath:t,metaMessages:r,name:"AccountTypeNotSupportedError"})}}function Th({chain:e,currentChainId:t}){if(!e)throw new Pw;if(t!==e.id)throw new Sw({chain:e,currentChainId:t})}function Ih(e,{docsPath:t,...r}){const n=(()=>{const i=ao(e,r);return i instanceof is?e:i})();return new ob(n,{docsPath:t,...r})}async function qu(e,{serializedTransaction:t}){return e.request({method:"eth_sendRawTransaction",params:[t]},{retryCount:0})}const Wo=new no(128);async function wo(e,t){var P,w,_,T;const{account:r=e.account,chain:n=e.chain,accessList:i,authorizationList:s,blobs:o,data:a,gas:c,gasPrice:f,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:y,nonce:p,type:g,value:b,...E}=t;if(typeof r>"u")throw new cn({docsPath:"/docs/actions/wallet/sendTransaction"});const A=r?ke(r):null;try{on(t);const I=await(async()=>{if(t.to)return t.to;if(t.to!==null&&s&&s.length>0)return await Gp({authorization:s[0]}).catch(()=>{throw new D("`to` is required. Could not infer from `authorizationList`.")})})();if((A==null?void 0:A.type)==="json-rpc"||A===null){let R;n!==null&&(R=await ee(e,Zn,"getChainId")({}),Th({currentChainId:R,chain:n}));const L=(_=(w=(P=e.chain)==null?void 0:P.formatters)==null?void 0:w.transactionRequest)==null?void 0:_.format,$=(L||Yn)({...co(E,{format:L}),accessList:i,authorizationList:s,blobs:o,chainId:R,data:a,from:A==null?void 0:A.address,gas:c,gasPrice:f,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:y,nonce:p,to:I,type:g,value:b}),C=Wo.get(e.uid),U=C?"wallet_sendTransaction":"eth_sendTransaction";try{return await e.request({method:U,params:[$]},{retryCount:0})}catch(j){if(C===!1)throw j;const V=j;if(V.name==="InvalidInputRpcError"||V.name==="InvalidParamsRpcError"||V.name==="MethodNotFoundRpcError"||V.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[$]},{retryCount:0}).then(Y=>(Wo.set(e.uid,!0),Y)).catch(Y=>{const X=Y;throw X.name==="MethodNotFoundRpcError"||X.name==="MethodNotSupportedRpcError"?(Wo.set(e.uid,!1),V):X});throw V}}if((A==null?void 0:A.type)==="local"){const R=await ee(e,lo,"prepareTransactionRequest")({account:A,accessList:i,authorizationList:s,blobs:o,chain:n,data:a,gas:c,gasPrice:f,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:y,nonce:p,nonceManager:A.nonceManager,parameters:[...oh,"sidecars"],type:g,value:b,...E,to:I}),L=(T=n==null?void 0:n.serializers)==null?void 0:T.transaction,S=await A.signTransaction(R,{serializer:L});return await ee(e,qu,"sendRawTransaction")({serializedTransaction:S})}throw(A==null?void 0:A.type)==="smart"?new $s({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new $s({docsPath:"/docs/actions/wallet/sendTransaction",type:A==null?void 0:A.type})}catch(I){throw I instanceof $s?I:Ih(I,{...t,account:A,chain:t.chain||void 0})}}async function kh(e,t){const{abi:r,account:n=e.account,address:i,args:s,dataSuffix:o,functionName:a,...c}=t;if(typeof n>"u")throw new cn({docsPath:"/docs/contract/writeContract"});const f=n?ke(n):null,u=xt({abi:r,args:s,functionName:a});try{return await ee(e,wo,"sendTransaction")({data:`${u}${o?o.replace("0x",""):""}`,to:i,account:f,...c})}catch(d){throw Jr(d,{abi:r,address:i,args:s,docsPath:"/docs/contract/writeContract",functionName:a,sender:f==null?void 0:f.address})}}function Ko({abi:e,address:t,client:r}){const n=r,[i,s]=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=i!=null,a=s!=null,c={};let f=!1,u=!1,d=!1;for(const y of e)if(y.type==="function"?y.stateMutability==="view"||y.stateMutability==="pure"?f=!0:u=!0:y.type==="event"&&(d=!0),f&&u&&d)break;return o&&(f&&(c.read=new Proxy({},{get(y,p){return(...g)=>{const{args:b,options:E}=bs(g);return ee(i,Wt,"readContract")({abi:e,address:t,functionName:p,args:b,...E})}}})),u&&(c.simulate=new Proxy({},{get(y,p){return(...g)=>{const{args:b,options:E}=bs(g);return ee(i,Sh,"simulateContract")({abi:e,address:t,functionName:p,args:b,...E})}}})),d&&(c.createEventFilter=new Proxy({},{get(y,p){return(...g)=>{const b=e.find(P=>P.type==="event"&&P.name===p),{args:E,options:A}=Yo(g,b);return ee(i,bu,"createContractEventFilter")({abi:e,address:t,eventName:p,args:E,...A})}}}),c.getEvents=new Proxy({},{get(y,p){return(...g)=>{const b=e.find(P=>P.type==="event"&&P.name===p),{args:E,options:A}=Yo(g,b);return ee(i,$u,"getContractEvents")({abi:e,address:t,eventName:p,args:E,...A})}}}),c.watchEvent=new Proxy({},{get(y,p){return(...g)=>{const b=e.find(P=>P.type==="event"&&P.name===p),{args:E,options:A}=Yo(g,b);return ee(i,Ph,"watchContractEvent")({abi:e,address:t,eventName:p,args:E,...A})}}}))),a&&u&&(c.write=new Proxy({},{get(y,p){return(...g)=>{const{args:b,options:E}=bs(g);return ee(s,kh,"writeContract")({abi:e,address:t,functionName:p,args:b,...E})}}})),(o||a)&&u&&(c.estimateGas=new Proxy({},{get(y,p){return(...g)=>{const{args:b,options:E}=bs(g);return ee(i??s,ch,"estimateContractGas")({abi:e,address:t,functionName:p,args:b,...E,account:E.account??s.account})}}})),c.address=t,c.abi=e,c}function bs(e){const t=e.length&&Array.isArray(e[0]),r=t?e[0]:[],n=(t?e[1]:e[0])??{};return{args:r,options:n}}function Yo(e,t){let r=!1;Array.isArray(e[0])?r=!0:e.length===1?r=t.inputs.some(s=>s.indexed):e.length===2&&(r=!0);const n=r?e[0]:void 0,i=(r?e[1]:e[0])??{};return{args:n,options:i}}const Bh={"0x0":"reverted","0x1":"success"};function Oh(e){const t={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map(r=>cr(r)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?vt(e.transactionIndex):null,status:e.status?Bh[e.status]:null,type:e.type?Wp[e.type]||e.type:null};return e.blobGasPrice&&(t.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(t.blobGasUsed=BigInt(e.blobGasUsed)),t}const Hw=xu("transactionReceipt",Oh),Ch="0x5792579257925792579257925792579257925792579257925792579257925792",Rh=K(0,{size:32});async function Lw(e,t){const{account:r=e.account,capabilities:n,chain:i=e.chain,experimental_fallback:s,experimental_fallbackDelay:o=32,forceAtomic:a=!1,id:c,version:f="2.0.0"}=t,u=r?ke(r):null,d=t.calls.map(y=>{const p=y,g=p.abi?xt({abi:p.abi,functionName:p.functionName,args:p.args}):p.data;return{data:p.dataSuffix&&g?ct([g,p.dataSuffix]):g,to:p.to,value:p.value?K(p.value):void 0}});try{const y=await e.request({method:"wallet_sendCalls",params:[{atomicRequired:a,calls:d,capabilities:n,chainId:K(i.id),from:u==null?void 0:u.address,id:c,version:f}]},{retryCount:0});return typeof y=="string"?{id:y}:y}catch(y){const p=y;if(s&&(p.name==="MethodNotFoundRpcError"||p.name==="MethodNotSupportedRpcError"||p.name==="UnknownRpcError"||p.details.toLowerCase().includes("does not exist / is not available")||p.details.toLowerCase().includes("missing or invalid. request()")||p.details.toLowerCase().includes("did not match any variant of untagged enum")||p.details.toLowerCase().includes("account upgraded to unsupported contract")||p.details.toLowerCase().includes("eip-7702 not supported")||p.details.toLowerCase().includes("unsupported wc_ method"))){if(n&&Object.values(n).some(P=>!P.optional)){const P="non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";throw new $n(new D(P,{details:P}))}if(a&&d.length>1){const A="`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";throw new Un(new D(A,{details:A}))}const g=[];for(const A of d){const P=wo(e,{account:u,chain:i,data:A.data,to:A.to,value:A.value?Ue(A.value):void 0});g.push(P),o>0&&await new Promise(w=>setTimeout(w,o))}const b=await Promise.allSettled(g);if(b.every(A=>A.status==="rejected"))throw b[0].reason;const E=b.map(A=>A.status==="fulfilled"?A.value:Rh);return{id:ct([...E,K(i.id,{size:32}),Ch])}}throw Ih(y,{...t,account:u,chain:t.chain})}}async function Nh(e,t){async function r(u){if(u.endsWith(Ch.slice(2))){const y=wt(Vs(u,-64,-32)),p=Vs(u,0,-64).slice(2).match(/.{1,64}/g),g=await Promise.all(p.map(E=>Rh.slice(2)!==E?e.request({method:"eth_getTransactionReceipt",params:[`0x${E}`]},{dedupe:!0}):void 0)),b=g.some(E=>E===null)?100:g.every(E=>(E==null?void 0:E.status)==="0x1")?200:g.every(E=>(E==null?void 0:E.status)==="0x0")?500:600;return{atomic:!1,chainId:vt(y),receipts:g.filter(Boolean),status:b,version:"2.0.0"}}return e.request({method:"wallet_getCallsStatus",params:[u]})}const{atomic:n=!1,chainId:i,receipts:s,version:o="2.0.0",...a}=await r(t.id),[c,f]=(()=>{const u=a.status;return u>=100&&u<200?["pending",u]:u>=200&&u<300?["success",u]:u>=300&&u<700?["failure",u]:u==="CONFIRMED"?["success",200]:u==="PENDING"?["pending",100]:[void 0,u]})();return{...a,atomic:n,chainId:i?vt(i):void 0,receipts:(s==null?void 0:s.map(u=>({...u,blockNumber:Ue(u.blockNumber),gasUsed:Ue(u.gasUsed),status:Bh[u.status]})))??[],statusCode:f,status:c,version:o}}async function Mw(e,t){const{id:r,pollingInterval:n=e.pollingInterval,status:i=({statusCode:y})=>y>=200,timeout:s=6e4}=t,o=Oe(["waitForCallsStatus",e.uid,r]),{promise:a,resolve:c,reject:f}=zu();let u;const d=ur(o,{resolve:c,reject:f},y=>{const p=Jn(async()=>{const g=b=>{clearTimeout(u),p(),b(),d()};try{const b=await Nh(e,{id:r});if(!i(b))return;g(()=>y.resolve(b))}catch(b){g(()=>y.reject(b))}},{interval:n,emitOnBegin:!0});return p});return u=s?setTimeout(()=>{d(),clearTimeout(u),f(new Dw({id:r}))},s):void 0,await a}class Dw extends D{constructor({id:t}){super(`Timed out while waiting for call bundle with id "${t}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}const Mc=256;let ws=Mc,vs;function Fh(e=11){if(!vs||ws+e>Mc*2){vs="",ws=0;for(let t=0;t<Mc;t++)vs+=(256+Math.random()*256|0).toString(16).substring(1)}return vs.substring(ws,ws+++e)}function $h(e){const{batch:t,chain:r,ccipRead:n,key:i="base",name:s="Base Client",type:o="base"}=e,a=(r==null?void 0:r.blockTime)??12e3,c=Math.min(Math.max(Math.floor(a/2),500),4e3),f=e.pollingInterval??c,u=e.cacheTime??f,d=e.account?ke(e.account):void 0,{config:y,request:p,value:g}=e.transport({chain:r,pollingInterval:f}),b={...y,...g},E={account:d,batch:t,cacheTime:u,ccipRead:n,chain:r,key:i,name:s,pollingInterval:f,request:p,transport:b,type:o,uid:Fh()};function A(P){return w=>{const _=w(P);for(const I in E)delete _[I];const T={...P,..._};return Object.assign(T,{extend:A(T)})}}return Object.assign(E,{extend:A(E)})}const Es=new no(8192);function jw(e,{enabled:t=!0,id:r}){if(!t||!r)return e();if(Es.get(r))return Es.get(r);const n=e().finally(()=>Es.delete(r));return Es.set(r,n),n}function Dc(e,{delay:t=100,retryCount:r=2,shouldRetry:n=()=>!0}={}){return new Promise((i,s)=>{const o=async({count:a=0}={})=>{const c=async({error:f})=>{const u=typeof t=="function"?t({count:a,error:f}):t;u&&await Lc(u),o({count:a+1})};try{const f=await e();i(f)}catch(f){if(a<r&&await n({count:a,error:f}))return c({error:f});s(f)}};o()})}function zw(e,t={}){return async(r,n={})=>{var d;const{dedupe:i=!1,methods:s,retryDelay:o=150,retryCount:a=3,uid:c}={...t,...n},{method:f}=r;if((d=s==null?void 0:s.exclude)!=null&&d.includes(f))throw new Lr(new Error("method not supported"),{method:f});if(s!=null&&s.include&&!s.include.includes(f))throw new Lr(new Error("method not supported"),{method:f});const u=i?Rn(`${c}.${Oe(r)}`):void 0;return jw(()=>Dc(async()=>{try{return await e(r)}catch(y){const p=y;switch(p.code){case Ii.code:throw new Ii(p);case ki.code:throw new ki(p);case Bi.code:throw new Bi(p,{method:r.method});case Oi.code:throw new Oi(p);case Zr.code:throw new Zr(p);case Xr.code:throw new Xr(p);case Ci.code:throw new Ci(p);case Ri.code:throw new Ri(p);case Ni.code:throw new Ni(p);case Lr.code:throw new Lr(p,{method:r.method});case Fn.code:throw new Fn(p);case Fi.code:throw new Fi(p);case Tn.code:throw new Tn(p);case $i.code:throw new $i(p);case Ui.code:throw new Ui(p);case Hi.code:throw new Hi(p);case Li.code:throw new Li(p);case Mi.code:throw new Mi(p);case $n.code:throw new $n(p);case Di.code:throw new Di(p);case ji.code:throw new ji(p);case zi.code:throw new zi(p);case qi.code:throw new qi(p);case Gi.code:throw new Gi(p);case Un.code:throw new Un(p);case 5e3:throw new Tn(p);default:throw y instanceof D?y:new pb(p)}}},{delay:({count:y,error:p})=>{var g;if(p&&p instanceof Pn){const b=(g=p==null?void 0:p.headers)==null?void 0:g.get("Retry-After");if(b!=null&&b.match(/\d/))return Number.parseInt(b)*1e3}return~~(1<<y)*o},retryCount:a,shouldRetry:({error:y})=>qw(y)}),{enabled:i,id:u})}}function qw(e){return"code"in e&&typeof e.code=="number"?e.code===-1||e.code===Fn.code||e.code===Zr.code:e instanceof Pn&&e.status?e.status===403||e.status===408||e.status===413||e.status===429||e.status===500||e.status===502||e.status===503||e.status===504:!0}function Uh({key:e,methods:t,name:r,request:n,retryCount:i=3,retryDelay:s=150,timeout:o,type:a},c){const f=Fh();return{config:{key:e,methods:t,name:r,request:n,retryCount:i,retryDelay:s,timeout:o,type:a},request:zw(n,{methods:t,retryCount:i,retryDelay:s,uid:f}),value:c}}function nd(e,t={}){const{key:r="custom",methods:n,name:i="Custom Provider",retryDelay:s}=t;return({retryCount:o})=>Uh({key:r,methods:n,name:i,request:e.request.bind(e),retryCount:t.retryCount??o,retryDelay:s,type:"custom"})}class Gw extends D{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(e,{errorInstance:t=new Error("timed out"),timeout:r,signal:n}){return new Promise((i,s)=>{(async()=>{let o;try{const a=new AbortController;r>0&&(o=setTimeout(()=>{n&&a.abort()},r)),i(await e({signal:(a==null?void 0:a.signal)||null}))}catch(a){(a==null?void 0:a.name)==="AbortError"&&s(t),s(a)}finally{clearTimeout(o)}})()})}function Ww(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const id=Ww();function Kw(e,t={}){return{async request(r){var d;const{body:n,onRequest:i=t.onRequest,onResponse:s=t.onResponse,timeout:o=t.timeout??1e4}=r,a={...t.fetchOptions??{},...r.fetchOptions??{}},{headers:c,method:f,signal:u}=a;try{const y=await Vw(async({signal:g})=>{const b={...a,body:Array.isArray(n)?Oe(n.map(w=>({jsonrpc:"2.0",id:w.id??id.take(),...w}))):Oe({jsonrpc:"2.0",id:n.id??id.take(),...n}),headers:{"Content-Type":"application/json",...c},method:f||"POST",signal:u||(o>0?g:null)},E=new Request(e,b),A=await(i==null?void 0:i(E,b))??{...b,url:e};return await fetch(A.url??e,A)},{errorInstance:new Df({body:n,url:e}),timeout:o,signal:!0});s&&await s(y);let p;if((d=y.headers.get("Content-Type"))!=null&&d.startsWith("application/json"))p=await y.json();else{p=await y.text();try{p=JSON.parse(p||"{}")}catch(g){if(y.ok)throw g;p={error:p}}}if(!y.ok)throw new Pn({body:n,details:Oe(p.error)||y.statusText,headers:y.headers,status:y.status,url:e});return p}catch(y){throw y instanceof Pn||y instanceof Df?y:new Pn({body:n,cause:y,url:e})}}}}function Hh(e,t={}){const{batch:r,fetchOptions:n,key:i="http",methods:s,name:o="HTTP JSON-RPC",onFetchRequest:a,onFetchResponse:c,retryDelay:f,raw:u}=t;return({chain:d,retryCount:y,timeout:p})=>{const{batchSize:g=1e3,wait:b=0}=typeof r=="object"?r:{},E=t.retryCount??y,A=p??t.timeout??1e4,P=d==null?void 0:d.rpcUrls.default.http[0];if(!P)throw new Gw;const w=Kw(P,{fetchOptions:n,onRequest:a,onResponse:c,timeout:A});return Uh({key:i,methods:s,name:o,async request({method:_,params:T}){const I={method:_,params:T},{schedule:R}=_h({id:P,wait:b,shouldSplitBatch(C){return C.length>g},fn:C=>w.request({body:C}),sort:(C,U)=>C.id-U.id}),L=async C=>r?R(C):[await w.request({body:C})],[{error:S,result:$}]=await L(I);if(u)return{error:S,result:$};if(S)throw new Eu({body:I,error:S,url:P});return $},retryCount:E,retryDelay:f,timeout:A,type:"http"},{fetchOptions:n,url:P})}}function Gu(e,t){var n,i,s,o,a,c;if(!(e instanceof D))return!1;const r=e.walk(f=>f instanceof Sc);return r instanceof Sc?!!(((n=r.data)==null?void 0:n.errorName)==="ResolverNotFound"||((i=r.data)==null?void 0:i.errorName)==="ResolverWildcardNotSupported"||((s=r.data)==null?void 0:s.errorName)==="ResolverNotContract"||((o=r.data)==null?void 0:o.errorName)==="ResolverError"||((a=r.data)==null?void 0:a.errorName)==="HttpError"||(c=r.reason)!=null&&c.includes("Wildcard on non-extended resolvers is not supported")||t==="reverse"&&r.reason===Rp[50]):!1}function Yw(e){const{abi:t,data:r}=e,n=Yr(r,0,4),i=t.find(s=>s.type==="function"&&n===es(Tt(s)));if(!i)throw new $m(n,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:i.name,args:"inputs"in i&&i.inputs&&i.inputs.length>0?rs(i.inputs,Yr(r,4)):void 0}}const Zo="/docs/contract/encodeErrorResult";function sd(e){const{abi:t,errorName:r,args:n}=e;let i=t[0];if(r){const c=sn({abi:t,args:n,name:r});if(!c)throw new Pf(r,{docsPath:Zo});i=c}if(i.type!=="error")throw new Pf(void 0,{docsPath:Zo});const s=Tt(i),o=es(s);let a="0x";if(n&&n.length>0){if(!i.inputs)throw new Nm(i.name,{docsPath:Zo});a=pr(i.inputs,n)}return Ct([o,a])}const Xo="/docs/contract/encodeFunctionResult";function Zw(e){const{abi:t,functionName:r,result:n}=e;let i=t[0];if(r){const o=sn({abi:t,name:r});if(!o)throw new Cn(r,{docsPath:Xo});i=o}if(i.type!=="function")throw new Cn(void 0,{docsPath:Xo});if(!i.outputs)throw new pp(i.name,{docsPath:Xo});const s=(()=>{if(i.outputs.length===0)return[];if(i.outputs.length===1)return[n];if(Array.isArray(n))return n;throw new hp(n)})();return pr(i.outputs,s)}const vo="x-batch-gateway:true";async function Lh(e){const{data:t,ccipRequest:r}=e,{args:[n]}=Yw({abi:Uc,data:t}),i=[],s=[];return await Promise.all(n.map(async(o,a)=>{try{s[a]=o.urls.includes(vo)?await Lh({data:o.data,ccipRequest:r}):await r(o),i[a]=!1}catch(c){i[a]=!0,s[a]=Xw(c)}})),Zw({abi:Uc,functionName:"query",result:[i,s]})}function Xw(e){return e.name==="HttpRequestError"&&e.status?sd({abi:Uc,errorName:"HttpError",args:[e.status,e.shortMessage]}):sd({abi:[Np],errorName:"Error",args:["shortMessage"in e?e.shortMessage:e.message]})}function Mh(e){if(e.length!==66||e.indexOf("[")!==0||e.indexOf("]")!==65)return null;const t=`0x${e.slice(1,65)}`;return It(t)?t:null}function Us(e){let t=new Uint8Array(32).fill(0);if(!e)return Ce(t);const r=e.split(".");for(let n=r.length-1;n>=0;n-=1){const i=Mh(r[n]),s=i?Kn(i):De(zr(r[n]),"bytes");t=De(ct([t,s]),"bytes")}return Ce(t)}function Jw(e){return`[${e.slice(2)}]`}function Qw(e){const t=new Uint8Array(32).fill(0);return e?Mh(e)||De(zr(e)):Ce(t)}function Eo(e){const t=e.replace(/^\.|\.$/gm,"");if(t.length===0)return new Uint8Array(1);const r=new Uint8Array(zr(t).byteLength+2);let n=0;const i=t.split(".");for(let s=0;s<i.length;s++){let o=zr(i[s]);o.byteLength>255&&(o=zr(Jw(Qw(i[s])))),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 e1(e,t){const{blockNumber:r,blockTag:n,coinType:i,name:s,gatewayUrls:o,strict:a}=t,{chain:c}=e,f=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Xn({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),u=c==null?void 0:c.ensTlds;if(u&&!u.some(d=>s.endsWith(d)))return null;try{const d=xt({abi:ed,functionName:"addr",...i!=null?{args:[Us(s),BigInt(i)]}:{args:[Us(s)]}}),y={address:f,abi:vh,functionName:"resolve",args:[je(Eo(s)),d,o??[vo]],blockNumber:r,blockTag:n},g=await ee(e,Wt,"readContract")(y);if(g[0]==="0x")return null;const b=an({abi:ed,args:i!=null?[Us(s),BigInt(i)]:void 0,functionName:"addr",data:g[0]});return b==="0x"||wt(b)==="0x00"?null:b}catch(d){if(a)throw d;if(Gu(d,"resolve"))return null;throw d}}class t1 extends D{constructor({data:t}){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(t)}`],name:"EnsAvatarInvalidMetadataError"})}}class ni extends D{constructor({reason:t}){super(`ENS NFT avatar URI is invalid. ${t}`,{name:"EnsAvatarInvalidNftUriError"})}}class Vu extends D{constructor({uri:t}){super(`Unable to resolve ENS avatar URI "${t}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class r1 extends D{constructor({namespace:t}){super(`ENS NFT avatar namespace "${t}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}const n1=/(?<protocol>https?:\/\/[^\/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,i1=/^(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>\/.*)?$/,s1=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,o1=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function a1(e){try{const t=await fetch(e,{method:"HEAD"});if(t.status===200){const r=t.headers.get("content-type");return r==null?void 0:r.startsWith("image/")}return!1}catch(t){return typeof t=="object"&&typeof t.response<"u"||!globalThis.hasOwnProperty("Image")?!1:new Promise(r=>{const n=new Image;n.onload=()=>{r(!0)},n.onerror=()=>{r(!1)},n.src=e})}}function od(e,t){return e?e.endsWith("/")?e.slice(0,-1):e:t}function Dh({uri:e,gatewayUrls:t}){const r=s1.test(e);if(r)return{uri:e,isOnChain:!0,isEncoded:r};const n=od(t==null?void 0:t.ipfs,"https://ipfs.io"),i=od(t==null?void 0:t.arweave,"https://arweave.net"),s=e.match(n1),{protocol:o,subpath:a,target:c,subtarget:f=""}=(s==null?void 0:s.groups)||{},u=o==="ipns:/"||a==="ipns/",d=o==="ipfs:/"||a==="ipfs/"||i1.test(e);if(e.startsWith("http")&&!u&&!d){let p=e;return t!=null&&t.arweave&&(p=e.replace(/https:\/\/arweave.net/g,t==null?void 0:t.arweave)),{uri:p,isOnChain:!1,isEncoded:!1}}if((u||d)&&c)return{uri:`${n}/${u?"ipns":"ipfs"}/${c}${f}`,isOnChain:!1,isEncoded:!1};if(o==="ar:/"&&c)return{uri:`${i}/${c}${f||""}`,isOnChain:!1,isEncoded:!1};let y=e.replace(o1,"");if(y.startsWith("<svg")&&(y=`data:image/svg+xml;base64,${btoa(y)}`),y.startsWith("data:")||y.startsWith("{"))return{uri:y,isOnChain:!0,isEncoded:!1};throw new Vu({uri:e})}function jh(e){if(typeof e!="object"||!("image"in e)&&!("image_url"in e)&&!("image_data"in e))throw new t1({data:e});return e.image||e.image_url||e.image_data}async function c1({gatewayUrls:e,uri:t}){try{const r=await fetch(t).then(i=>i.json());return await Wu({gatewayUrls:e,uri:jh(r)})}catch{throw new Vu({uri:t})}}async function Wu({gatewayUrls:e,uri:t}){const{uri:r,isOnChain:n}=Dh({uri:t,gatewayUrls:e});if(n||await a1(r))return r;throw new Vu({uri:t})}function u1(e){let t=e;t.startsWith("did:nft:")&&(t=t.replace("did:nft:","").replace(/_/g,"/"));const[r,n,i]=t.split("/"),[s,o]=r.split(":"),[a,c]=n.split(":");if(!s||s.toLowerCase()!=="eip155")throw new ni({reason:"Only EIP-155 supported"});if(!o)throw new ni({reason:"Chain ID not found"});if(!c)throw new ni({reason:"Contract address not found"});if(!i)throw new ni({reason:"Token ID not found"});if(!a)throw new ni({reason:"ERC namespace not found"});return{chainID:Number.parseInt(o),namespace:a.toLowerCase(),contractAddress:c,tokenID:i}}async function f1(e,{nft:t}){if(t.namespace==="erc721")return Wt(e,{address:t.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(t.tokenID)]});if(t.namespace==="erc1155")return Wt(e,{address:t.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(t.tokenID)]});throw new r1({namespace:t.namespace})}async function d1(e,{gatewayUrls:t,record:r}){return/eip155:/i.test(r)?l1(e,{gatewayUrls:t,record:r}):Wu({uri:r,gatewayUrls:t})}async function l1(e,{gatewayUrls:t,record:r}){const n=u1(r),i=await f1(e,{nft:n}),{uri:s,isOnChain:o,isEncoded:a}=Dh({uri:i,gatewayUrls:t});if(o&&(s.includes("data:application/json;base64,")||s.startsWith("{"))){const f=a?atob(s.replace("data:application/json;base64,","")):s,u=JSON.parse(f);return Wu({uri:jh(u),gatewayUrls:t})}let c=n.tokenID;return n.namespace==="erc1155"&&(c=c.replace("0x","").padStart(64,"0")),c1({gatewayUrls:t,uri:s.replace(/(?:0x)?{id}/,c)})}async function zh(e,t){const{blockNumber:r,blockTag:n,key:i,name:s,gatewayUrls:o,strict:a}=t,{chain:c}=e,f=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Xn({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),u=c==null?void 0:c.ensTlds;if(u&&!u.some(d=>s.endsWith(d)))return null;try{const d={address:f,abi:vh,functionName:"resolve",args:[je(Eo(s)),xt({abi:Qf,functionName:"text",args:[Us(s),i]}),o??[vo]],blockNumber:r,blockTag:n},p=await ee(e,Wt,"readContract")(d);if(p[0]==="0x")return null;const g=an({abi:Qf,functionName:"text",data:p[0]});return g===""?null:g}catch(d){if(a)throw d;if(Gu(d,"resolve"))return null;throw d}}async function p1(e,{blockNumber:t,blockTag:r,assetGatewayUrls:n,name:i,gatewayUrls:s,strict:o,universalResolverAddress:a}){const c=await ee(e,zh,"getEnsText")({blockNumber:t,blockTag:r,key:"avatar",name:i,universalResolverAddress:a,gatewayUrls:s,strict:o});if(!c)return null;try{return await d1(e,{record:c,gatewayUrls:n})}catch{return null}}async function h1(e,{address:t,blockNumber:r,blockTag:n,gatewayUrls:i,strict:s,universalResolverAddress:o}){let a=o;if(!a){if(!e.chain)throw new Error("client chain not configured. universalResolverAddress is required.");a=Xn({blockNumber:r,chain:e.chain,contract:"ensUniversalResolver"})}const c=`${t.toLowerCase().substring(2)}.addr.reverse`;try{const f={address:a,abi:Ew,functionName:"reverse",args:[je(Eo(c))],blockNumber:r,blockTag:n},u=ee(e,Wt,"readContract"),[d,y]=i?await u({...f,args:[...f.args,i]}):await u(f);return t.toLowerCase()!==y.toLowerCase()?null:d}catch(f){if(s)throw f;if(Gu(f,"reverse"))return null;throw f}}async function y1(e,t){const{blockNumber:r,blockTag:n,name:i}=t,{chain:s}=e,o=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!s)throw new Error("client chain not configured. universalResolverAddress is required.");return Xn({blockNumber:r,chain:s,contract:"ensUniversalResolver"})})(),a=s==null?void 0:s.ensTlds;if(a&&!a.some(f=>i.endsWith(f)))throw new Error(`${i} is not a valid ENS TLD (${a==null?void 0:a.join(", ")}) for chain "${s.name}" (id: ${s.id}).`);const[c]=await ee(e,Wt,"readContract")({address:o,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[je(Eo(i))],blockNumber:r,blockTag:n});return c}async function qh(e,t){var E,A,P;const{account:r=e.account,blockNumber:n,blockTag:i="latest",blobs:s,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:f,maxFeePerGas:u,maxPriorityFeePerGas:d,to:y,value:p,...g}=t,b=r?ke(r):void 0;try{on(t);const _=(typeof n=="bigint"?K(n):void 0)||i,T=(P=(A=(E=e.chain)==null?void 0:E.formatters)==null?void 0:A.transactionRequest)==null?void 0:P.format,R=(T||Yn)({...co(g,{format:T}),from:b==null?void 0:b.address,blobs:s,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:f,maxFeePerGas:u,maxPriorityFeePerGas:d,to:y,value:p}),L=await e.request({method:"eth_createAccessList",params:[R,_]});return{accessList:L.accessList,gasUsed:BigInt(L.gasUsed)}}catch(w){throw Ah(w,{...t,account:b,chain:e.chain})}}async function m1(e){const t=io(e,{method:"eth_newBlockFilter"}),r=await e.request({method:"eth_newBlockFilter"});return{id:r,request:t(r),type:"block"}}async function Gh(e,{address:t,args:r,event:n,events:i,fromBlock:s,strict:o,toBlock:a}={}){const c=i??(n?[n]:void 0),f=io(e,{method:"eth_newFilter"});let u=[];c&&(u=[c.flatMap(p=>ts({abi:[p],eventName:p.name,args:r}))],n&&(u=u[0]));const d=await e.request({method:"eth_newFilter",params:[{address:t,fromBlock:typeof s=="bigint"?K(s):s,toBlock:typeof a=="bigint"?K(a):a,...u.length?{topics:u}:{}}]});return{abi:c,args:r,eventName:n?n.name:void 0,fromBlock:s,id:d,request:f(d),strict:!!o,toBlock:a,type:"event"}}async function Vh(e){const t=io(e,{method:"eth_newPendingTransactionFilter"}),r=await e.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:t(r),type:"transaction"}}async function g1(e){const t=await e.request({method:"eth_blobBaseFee"});return BigInt(t)}async function b1(e,{blockHash:t,blockNumber:r,blockTag:n="latest"}={}){const i=r!==void 0?K(r):void 0;let s;return t?s=await e.request({method:"eth_getBlockTransactionCountByHash",params:[t]},{dedupe:!0}):s=await e.request({method:"eth_getBlockTransactionCountByNumber",params:[i||n]},{dedupe:!!i}),vt(s)}async function ad(e,{address:t,blockNumber:r,blockTag:n="latest"}){const i=r!==void 0?K(r):void 0,s=await e.request({method:"eth_getCode",params:[t,i||n]},{dedupe:!!i});if(s!=="0x")return s}class w1 extends D{constructor({address:t}){super(`No EIP-712 domain found on contract "${t}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${t}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}async function v1(e,t){const{address:r,factory:n,factoryData:i}=t;try{const[s,o,a,c,f,u,d]=await ee(e,Wt,"readContract")({abi:E1,address:r,functionName:"eip712Domain",factory:n,factoryData:i});return{domain:{name:o,version:a,chainId:Number(c),verifyingContract:f,salt:u},extensions:d,fields:s}}catch(s){const o=s;throw o.name==="ContractFunctionExecutionError"&&o.cause.name==="ContractFunctionZeroDataError"?new w1({address:r}):o}}const E1=[{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 x1(e){var t;return{baseFeePerGas:e.baseFeePerGas.map(r=>BigInt(r)),gasUsedRatio:e.gasUsedRatio,oldestBlock:BigInt(e.oldestBlock),reward:(t=e.reward)==null?void 0:t.map(r=>r.map(n=>BigInt(n)))}}async function A1(e,{blockCount:t,blockNumber:r,blockTag:n="latest",rewardPercentiles:i}){const s=typeof r=="bigint"?K(r):void 0,o=await e.request({method:"eth_feeHistory",params:[K(t),s||n,i]},{dedupe:!!s});return x1(o)}async function _1(e,{filter:t}){const r=t.strict??!1,i=(await t.request({method:"eth_getFilterLogs",params:[t.id]})).map(s=>cr(s));return t.abi?Nu({abi:t.abi,logs:i,strict:r}):i}function At(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}class S1 extends D{constructor({domain:t}){super(`Invalid domain "${Oe(t)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class P1 extends D{constructor({primaryType:t,types:r}){super(`Invalid primary type \`${t}\` 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 T1 extends D{constructor({type:t}){super(`Struct type "${t}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}function I1(e){const{domain:t={},message:r,primaryType:n}=e,i={EIP712Domain:Jh({domain:t}),...e.types};Xh({domain:t,message:r,primaryType:n,types:i});const s=["0x1901"];return t&&s.push(k1({domain:t,types:i})),n!=="EIP712Domain"&&s.push(Wh({data:r,primaryType:n,types:i})),De(ct(s))}function k1({domain:e,types:t}){return Wh({data:e,primaryType:"EIP712Domain",types:t})}function Wh({data:e,primaryType:t,types:r}){const n=Kh({data:e,primaryType:t,types:r});return De(n)}function Kh({data:e,primaryType:t,types:r}){const n=[{type:"bytes32"}],i=[B1({primaryType:t,types:r})];for(const s of r[t]){const[o,a]=Zh({types:r,name:s.name,type:s.type,value:e[s.name]});n.push(o),i.push(a)}return pr(n,i)}function B1({primaryType:e,types:t}){const r=je(O1({primaryType:e,types:t}));return De(r)}function O1({primaryType:e,types:t}){let r="";const n=Yh({primaryType:e,types:t});n.delete(e);const i=[e,...Array.from(n).sort()];for(const s of i)r+=`${s}(${t[s].map(({name:o,type:a})=>`${a} ${o}`).join(",")})`;return r}function Yh({primaryType:e,types:t},r=new Set){const n=e.match(/^\w*/u),i=n==null?void 0:n[0];if(r.has(i)||t[i]===void 0)return r;r.add(i);for(const s of t[i])Yh({primaryType:s.type,types:t},r);return r}function Zh({types:e,name:t,type:r,value:n}){if(e[r]!==void 0)return[{type:"bytes32"},De(Kh({data:n,primaryType:r,types:e}))];if(r==="bytes")return n=`0x${(n.length%2?"0":"")+n.slice(2)}`,[{type:"bytes32"},De(n)];if(r==="string")return[{type:"bytes32"},De(je(n))];if(r.lastIndexOf("]")===r.length-1){const i=r.slice(0,r.lastIndexOf("[")),s=n.map(o=>Zh({name:t,type:i,types:e,value:o}));return[{type:"bytes32"},De(pr(s.map(([o])=>o),s.map(([,o])=>o)))]}return[{type:r},n]}function C1(e){const{domain:t,message:r,primaryType:n,types:i}=e,s=(c,f)=>{const u={...f};for(const d of c){const{name:y,type:p}=d;p==="address"&&(u[y]=u[y].toLowerCase())}return u},o=i.EIP712Domain?t?s(i.EIP712Domain,t):{}:{},a=(()=>{if(n!=="EIP712Domain")return s(i[n],r)})();return Oe({domain:o,message:a,primaryType:n,types:i})}function Xh(e){const{domain:t,message:r,primaryType:n,types:i}=e,s=(o,a)=>{for(const c of o){const{name:f,type:u}=c,d=a[f],y=u.match(Op);if(y&&(typeof d=="number"||typeof d=="bigint")){const[b,E,A]=y;K(d,{signed:E==="int",size:Number.parseInt(A)/8})}if(u==="address"&&typeof d=="string"&&!Fe(d))throw new tt({address:d});const p=u.match(Ig);if(p){const[b,E]=p;if(E&&Se(d)!==Number.parseInt(E))throw new Hm({expectedSize:Number.parseInt(E),givenSize:Se(d)})}const g=i[u];g&&(R1(u),s(g,d))}};if(i.EIP712Domain&&t){if(typeof t!="object")throw new S1({domain:t});s(i.EIP712Domain,t)}if(n!=="EIP712Domain")if(i[n])s(i[n],r);else throw new P1({primaryType:n,types:i})}function Jh({domain:e}){return[typeof(e==null?void 0:e.name)=="string"&&{name:"name",type:"string"},(e==null?void 0:e.version)&&{name:"version",type:"string"},(typeof(e==null?void 0:e.chainId)=="number"||typeof(e==null?void 0:e.chainId)=="bigint")&&{name:"chainId",type:"uint256"},(e==null?void 0:e.verifyingContract)&&{name:"verifyingContract",type:"address"},(e==null?void 0:e.salt)&&{name:"salt",type:"bytes32"}].filter(Boolean)}function R1(e){if(e==="address"||e==="bool"||e==="string"||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new T1({type:e})}function N1(e){const{authorizationList:t}=e;if(t)for(const r of t){const{chainId:n}=r,i=r.address;if(!Fe(i))throw new tt({address:i});if(n<0)throw new yo({chainId:n})}Ku(e)}function F1(e){const{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new nh;for(const r of t){const n=Se(r),i=vt(Yr(r,0,1));if(n!==32)throw new zb({hash:r,size:n});if(i!==rh)throw new qb({hash:r,version:i})}}Ku(e)}function Ku(e){const{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:i}=e;if(t<=0)throw new yo({chainId:t});if(i&&!Fe(i))throw new tt({address:i});if(n&&n>uo)throw new Qr({maxFeePerGas:n});if(r&&n&&r>n)throw new Vi({maxFeePerGas:n,maxPriorityFeePerGas:r})}function $1(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:s}=e;if(t<=0)throw new yo({chainId:t});if(s&&!Fe(s))throw new tt({address:s});if(r||i)throw new D("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>uo)throw new Qr({maxFeePerGas:n})}function U1(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:s}=e;if(s&&!Fe(s))throw new tt({address:s});if(typeof t<"u"&&t<=0)throw new yo({chainId:t});if(r||i)throw new D("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>uo)throw new Qr({maxFeePerGas:n})}function xo(e){if(!e||e.length===0)return[];const t=[];for(let r=0;r<e.length;r++){const{address:n,storageKeys:i}=e[r];for(let s=0;s<i.length;s++)if(i[s].length-2!==64)throw new sb({storageKey:i[s]});if(!Fe(n,{strict:!1}))throw new tt({address:n});t.push([n,i])}return t}function H1(e,t){const r=sh(e);return r==="eip1559"?D1(e,t):r==="eip2930"?j1(e,t):r==="eip4844"?M1(e,t):r==="eip7702"?L1(e,t):z1(e,t)}function L1(e,t){const{authorizationList:r,chainId:n,gas:i,nonce:s,to:o,value:a,maxFeePerGas:c,maxPriorityFeePerGas:f,accessList:u,data:d}=e;N1(e);const y=xo(u),p=q1(r);return Ct(["0x04",Cr([K(n),s?K(s):"0x",f?K(f):"0x",c?K(c):"0x",i?K(i):"0x",o??"0x",a?K(a):"0x",d??"0x",y,p,...cs(e,t)])])}function M1(e,t){const{chainId:r,gas:n,nonce:i,to:s,value:o,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:f,accessList:u,data:d}=e;F1(e);let y=e.blobVersionedHashes,p=e.sidecars;if(e.blobs&&(typeof y>"u"||typeof p>"u")){const w=typeof e.blobs[0]=="string"?e.blobs:e.blobs.map(I=>Ce(I)),_=e.kzg,T=Iu({blobs:w,kzg:_});if(typeof y>"u"&&(y=Qp({commitments:T})),typeof p>"u"){const I=ku({blobs:w,commitments:T,kzg:_});p=ih({blobs:w,commitments:T,proofs:I})}}const g=xo(u),b=[K(r),i?K(i):"0x",f?K(f):"0x",c?K(c):"0x",n?K(n):"0x",s??"0x",o?K(o):"0x",d??"0x",g,a?K(a):"0x",y??[],...cs(e,t)],E=[],A=[],P=[];if(p)for(let w=0;w<p.length;w++){const{blob:_,commitment:T,proof:I}=p[w];E.push(_),A.push(T),P.push(I)}return Ct(["0x03",Cr(p?[b,E,A,P]:b)])}function D1(e,t){const{chainId:r,gas:n,nonce:i,to:s,value:o,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:f,data:u}=e;Ku(e);const d=xo(f),y=[K(r),i?K(i):"0x",c?K(c):"0x",a?K(a):"0x",n?K(n):"0x",s??"0x",o?K(o):"0x",u??"0x",d,...cs(e,t)];return Ct(["0x02",Cr(y)])}function j1(e,t){const{chainId:r,gas:n,data:i,nonce:s,to:o,value:a,accessList:c,gasPrice:f}=e;$1(e);const u=xo(c),d=[K(r),s?K(s):"0x",f?K(f):"0x",n?K(n):"0x",o??"0x",a?K(a):"0x",i??"0x",u,...cs(e,t)];return Ct(["0x01",Cr(d)])}function z1(e,t){const{chainId:r=0,gas:n,data:i,nonce:s,to:o,value:a,gasPrice:c}=e;U1(e);let f=[s?K(s):"0x",c?K(c):"0x",n?K(n):"0x",o??"0x",a?K(a):"0x",i??"0x"];if(t){const u=(()=>{if(t.v>=35n)return(t.v-35n)/2n>0?t.v:27n+(t.v===35n?0n:1n);if(r>0)return BigInt(r*2)+BigInt(35n+t.v-27n);const p=27n+(t.v===27n?0n:1n);if(t.v!==p)throw new nb({v:t.v});return p})(),d=wt(t.r),y=wt(t.s);f=[...f,K(u),d==="0x00"?"0x":d,y==="0x00"?"0x":y]}else r>0&&(f=[...f,K(r),"0x","0x"]);return Cr(f)}function cs(e,t){const r=t??e,{v:n,yParity:i}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof i>"u")return[];const s=wt(r.r),o=wt(r.s);return[typeof i=="number"?i?K(1):"0x":n===0n?"0x":n===1n?K(1):n===27n?"0x":K(1),s==="0x00"?"0x":s,o==="0x00"?"0x":o]}function q1(e){if(!e||e.length===0)return[];const t=[];for(const r of e){const{chainId:n,nonce:i,...s}=r,o=r.address;t.push([n?je(n):"0x",o,i?je(i):"0x",...cs({},s)])}return t}const G1=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Qh=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),V1=Qh.map(e=>(9*e+5)%16),e0=(()=>{const r=[[Qh],[V1]];for(let n=0;n<4;n++)for(let i of r)i.push(i[n].map(s=>G1[s]));return r})(),t0=e0[0],r0=e0[1],n0=[[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(e=>Uint8Array.from(e)),W1=t0.map((e,t)=>e.map(r=>n0[t][r])),K1=r0.map((e,t)=>e.map(r=>n0[t][r])),Y1=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Z1=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function cd(e,t,r,n){return e===0?t^r^n:e===1?t&r|~t&n:e===2?(t|~r)^n:e===3?t&n|r&~n:t^(r|~n)}const xs=new Uint32Array(16);let i0=class extends Yp{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:t,h1:r,h2:n,h3:i,h4:s}=this;return[t,r,n,i,s]}set(t,r,n,i,s){this.h0=t|0,this.h1=r|0,this.h2=n|0,this.h3=i|0,this.h4=s|0}process(t,r){for(let p=0;p<16;p++,r+=4)xs[p]=t.getUint32(r,!0);let n=this.h0|0,i=n,s=this.h1|0,o=s,a=this.h2|0,c=a,f=this.h3|0,u=f,d=this.h4|0,y=d;for(let p=0;p<5;p++){const g=4-p,b=Y1[p],E=Z1[p],A=t0[p],P=r0[p],w=W1[p],_=K1[p];for(let T=0;T<16;T++){const I=ms(n+cd(p,s,a,f)+xs[A[T]]+b,w[T])+d|0;n=d,d=f,f=ms(a,10)|0,a=s,s=I}for(let T=0;T<16;T++){const I=ms(i+cd(g,o,c,u)+xs[P[T]]+E,_[T])+y|0;i=y,y=u,u=ms(c,10)|0,c=o,o=I}}this.set(this.h1+a+u|0,this.h2+f+y|0,this.h3+d+i|0,this.h4+n+o|0,this.h0+s+c|0)}roundClean(){Or(xs)}destroy(){this.destroyed=!0,Or(this.buffer),this.set(0,0,0,0,0)}};const X1=to(()=>new i0),J1=i0,Q1=X1,e2=Object.freeze(Object.defineProperty({__proto__:null,RIPEMD160:J1,ripemd160:Q1},Symbol.toStringTag,{value:"Module"})),t2=`Ethereum Signed Message:
43
- `;function r2(e){const t=typeof e=="string"?Rn(e):typeof e.raw=="string"?e.raw:Ce(e.raw),r=Rn(`${t2}${Se(t)}`);return ct([r,t])}function s0(e,t){return De(r2(e),t)}const o0="0x6492649264926492649264926492649264926492649264926492649264926492";function n2(e){return Vs(e,-32)===o0}function i2(e){const{address:t,data:r,signature:n,to:i="hex"}=e,s=Ct([pr([{type:"address"},{type:"bytes"},{type:"bytes"}],[t,r,n]),o0]);return i==="hex"?s:kt(s)}function s2(e){return e.map(t=>({...t,value:BigInt(t.value)}))}function o2(e){return{...e,balance:e.balance?BigInt(e.balance):void 0,nonce:e.nonce?vt(e.nonce):void 0,storageProof:e.storageProof?s2(e.storageProof):void 0}}async function a2(e,{address:t,blockNumber:r,blockTag:n,storageKeys:i}){const s=n??"latest",o=r!==void 0?K(r):void 0,a=await e.request({method:"eth_getProof",params:[t,i,o||s]});return o2(a)}async function c2(e,{address:t,blockNumber:r,blockTag:n="latest",slot:i}){const s=r!==void 0?K(r):void 0;return await e.request({method:"eth_getStorageAt",params:[t,i,s||n]})}async function Yu(e,{blockHash:t,blockNumber:r,blockTag:n,hash:i,index:s}){var u,d,y;const o=n||"latest",a=r!==void 0?K(r):void 0;let c=null;if(i?c=await e.request({method:"eth_getTransactionByHash",params:[i]},{dedupe:!0}):t?c=await e.request({method:"eth_getTransactionByBlockHashAndIndex",params:[t,K(s)]},{dedupe:!0}):c=await e.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[a||o,K(s)]},{dedupe:!!a}),!c)throw new Lp({blockHash:t,blockNumber:r,blockTag:o,hash:i,index:s});return(((y=(d=(u=e.chain)==null?void 0:u.formatters)==null?void 0:d.transaction)==null?void 0:y.format)||fo)(c)}async function u2(e,{hash:t,transactionReceipt:r}){const[n,i]=await Promise.all([ee(e,as,"getBlockNumber")({}),t?ee(e,Yu,"getTransaction")({hash:t}):void 0]),s=(r==null?void 0:r.blockNumber)||(i==null?void 0:i.blockNumber);return s?n-s+1n:0n}async function jc(e,{hash:t}){var i,s,o;const r=await e.request({method:"eth_getTransactionReceipt",params:[t]},{dedupe:!0});if(!r)throw new Mp({hash:t});return(((o=(s=(i=e.chain)==null?void 0:i.formatters)==null?void 0:s.transactionReceipt)==null?void 0:o.format)||Oh)(r)}async function f2(e,t){var A;const{account:r,allowFailure:n=!0,batchSize:i,blockNumber:s,blockTag:o,multicallAddress:a,stateOverride:c}=t,f=t.contracts,u=i??(typeof((A=e.batch)==null?void 0:A.multicall)=="object"&&e.batch.multicall.batchSize||1024);let d=a;if(!d){if(!e.chain)throw new Error("client chain not configured. multicallAddress is required.");d=Xn({blockNumber:s,chain:e.chain,contract:"multicall3"})}const y=[[]];let p=0,g=0;for(let P=0;P<f.length;P++){const{abi:w,address:_,args:T,functionName:I}=f[P];try{const R=xt({abi:w,args:T,functionName:I});g+=(R.length-2)/2,u>0&&g>u&&y[p].length>0&&(p++,g=(R.length-2)/2,y[p]=[]),y[p]=[...y[p],{allowFailure:!0,callData:R,target:_}]}catch(R){const L=Jr(R,{abi:w,address:_,args:T,docsPath:"/docs/contract/multicall",functionName:I,sender:r});if(!n)throw L;y[p]=[...y[p],{allowFailure:!0,callData:"0x",target:_}]}}const b=await Promise.allSettled(y.map(P=>ee(e,Wt,"readContract")({abi:$c,account:r,address:d,args:[P],blockNumber:s,blockTag:o,functionName:"aggregate3",stateOverride:c}))),E=[];for(let P=0;P<b.length;P++){const w=b[P];if(w.status==="rejected"){if(!n)throw w.reason;for(let T=0;T<y[P].length;T++)E.push({status:"failure",error:w.reason,result:void 0});continue}const _=w.value;for(let T=0;T<_.length;T++){const{returnData:I,success:R}=_[T],{callData:L}=y[P][T],{abi:S,address:$,functionName:C,args:U}=f[E.length];try{if(L==="0x")throw new Ji;if(!R)throw new oo({data:I});const j=an({abi:S,args:U,data:I,functionName:C});E.push(n?{result:j,status:"success"}:j)}catch(j){const V=Jr(j,{abi:S,address:$,args:U,docsPath:"/docs/contract/multicall",functionName:C});if(!n)throw V;E.push({error:V,result:void 0,status:"failure"})}}}if(E.length!==f.length)throw new D("multicall results mismatch");return E}async function zc(e,t){const{blockNumber:r,blockTag:n="latest",blocks:i,returnFullTransactions:s,traceTransfers:o,validation:a}=t;try{const c=[];for(const y of i){const p=y.blockOverrides?bh(y.blockOverrides):void 0,g=y.calls.map(E=>{const A=E,P=A.account?ke(A.account):void 0,w=A.abi?xt(A):A.data,_={...A,data:A.dataSuffix?ct([w||"0x",A.dataSuffix]):w,from:A.from??(P==null?void 0:P.address)};return on(_),Yn(_)}),b=y.stateOverrides?Au(y.stateOverrides):void 0;c.push({blockOverrides:p,calls:g,stateOverrides:b})}const u=(typeof r=="bigint"?K(r):void 0)||n;return(await e.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:s,traceTransfers:o,validation:a},u]})).map((y,p)=>({...Su(y),calls:y.calls.map((g,b)=>{var $,C;const{abi:E,args:A,functionName:P,to:w}=i[p].calls[b],_=(($=g.error)==null?void 0:$.data)??g.returnData,T=BigInt(g.gasUsed),I=(C=g.logs)==null?void 0:C.map(U=>cr(U)),R=g.status==="0x1"?"success":"failure",L=E&&R==="success"&&_!=="0x"?an({abi:E,data:_,functionName:P}):null,S=(()=>{var j;if(R==="success")return;let U;if(((j=g.error)==null?void 0:j.data)==="0x"?U=new Ji:g.error&&(U=new oo(g.error)),!!U)return Jr(U,{abi:E??[],address:w??"0x",args:A,functionName:P??"<unknown>"})})();return{data:_,gasUsed:T,logs:I,status:R,...R==="success"?{result:L}:{error:S}}})}))}catch(c){const f=c,u=ao(f,{});throw u instanceof is?f:u}}function a0(e,t={}){const{as:r=typeof e=="string"?"Hex":"Bytes"}=t,n=Sp(aw(e));return r==="Bytes"?n:yh(n)}class d2 extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){const r=super.get(t);return super.has(t)&&r!==void 0&&(this.delete(t),super.set(t,r)),r}set(t,r){if(super.set(t,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const l2={checksum:new d2(8192)},Jo=l2.checksum,p2=/^0x[a-fA-F0-9]{40}$/;function Ao(e,t={}){const{strict:r=!0}=t;if(!p2.test(e))throw new ud({address:e,cause:new y2});if(r){if(e.toLowerCase()===e)return;if(h2(e)!==e)throw new ud({address:e,cause:new m2})}}function h2(e){if(Jo.has(e))return Jo.get(e);Ao(e,{strict:!1});const t=e.substring(2).toLowerCase(),r=a0(fw(t),{as:"Bytes"}),n=t.split("");for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&n[s]&&(n[s]=n[s].toUpperCase()),(r[s>>1]&15)>=8&&n[s+1]&&(n[s+1]=n[s+1].toUpperCase());const i=`0x${n.join("")}`;return Jo.set(e,i),i}function qc(e,t={}){const{strict:r=!0}=t??{};try{return Ao(e,{strict:r}),!0}catch{return!1}}class ud extends xe{constructor({address:t,cause:r}){super(`Address "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class y2 extends xe{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 m2 extends xe{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}function Gc(e){let t=!0,r="",n=0,i="",s=!1;for(let o=0;o<e.length;o++){const a=e[o];if(["(",")",","].includes(a)&&(t=!0),a==="("&&n++,a===")"&&n--,!!t){if(n===0){if(a===" "&&["event","function","error",""].includes(i))i="";else if(i+=a,a===")"){s=!0;break}continue}if(a===" "){e[o-1]!==","&&r!==","&&r!==",("&&(r="",t=!1);continue}i+=a,r+=a}}if(!s)throw new xe("Unable to normalize signature.");return i}function Vc(e,t){const r=typeof e,n=t.type;switch(n){case"address":return qc(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in t?Object.values(t.components).every((i,s)=>Vc(Object.values(e)[s],i)):/^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"||e instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(e)&&e.every(i=>Vc(i,{...t,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function c0(e,t,r){for(const n in e){const i=e[n],s=t[n];if(i.type==="tuple"&&s.type==="tuple"&&"components"in i&&"components"in s)return c0(i.components,s.components,r[n]);const o=[i.type,s.type];if(o.includes("address")&&o.includes("bytes20")?!0:o.includes("address")&&o.includes("string")?qc(r[n],{strict:!1}):o.includes("address")&&o.includes("bytes")?qc(r[n],{strict:!1}):!1)return o}}function u0(e,t={}){const{prepare:r=!0}=t,n=Array.isArray(e)||typeof e=="string"?_f(e):e;return{...n,...r?{hash:_n(n)}:{}}}function g2(e,t,r){const{args:n=[],prepare:i=!0}=r??{},s=gw(t,{strict:!1}),o=e.filter(f=>s?f.type==="function"||f.type==="error"?f0(f)===ju(t,0,4):f.type==="event"?_n(f)===t:!1:"name"in f&&f.name===t);if(o.length===0)throw new Wc({name:t});if(o.length===1)return{...o[0],...i?{hash:_n(o[0])}:{}};let a;for(const f of o){if(!("inputs"in f))continue;if(!n||n.length===0){if(!f.inputs||f.inputs.length===0)return{...f,...i?{hash:_n(f)}:{}};continue}if(!f.inputs||f.inputs.length===0||f.inputs.length!==n.length)continue;if(n.every((d,y)=>{const p="inputs"in f&&f.inputs[y];return p?Vc(d,p):!1})){if(a&&"inputs"in a&&a.inputs){const d=c0(f.inputs,a.inputs,n);if(d)throw new w2({abiItem:f,type:d[0]},{abiItem:a,type:d[1]})}a=f}}const c=(()=>{if(a)return a;const[f,...u]=o;return{...f,overloads:u}})();if(!c)throw new Wc({name:t});return{...c,...i?{hash:_n(c)}:{}}}function f0(e){return ju(_n(e),0,4)}function b2(e){const t=typeof e=="string"?e:Gs(e);return Gc(t)}function _n(e){return typeof e!="string"&&"hash"in e&&e.hash?e.hash:a0(Du(b2(e)))}class w2 extends xe{constructor(t,r){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${t.type}\` in \`${Gc(Gs(t.abiItem))}\`, and`,`\`${r.type}\` in \`${Gc(Gs(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 Wc extends xe{constructor({name:t,data:r,type:n="item"}){const i=t?` with name "${t}"`:r?` with data "${r}"`:"";super(`ABI ${n}${i} not found.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}const v2=/^(.*)\[([0-9]*)\]$/,E2=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,d0=/^(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 x2({checksumAddress:e,parameters:t,values:r}){const n=[];for(let i=0;i<t.length;i++)n.push(Zu({checksumAddress:e,parameter:t[i],value:r[i]}));return n}function Zu({checksumAddress:e=!1,parameter:t,value:r}){const n=t,i=B2(n.type);if(i){const[s,o]=i;return _2(r,{checksumAddress:e,length:s,parameter:{...n,type:o}})}if(n.type==="tuple")return k2(r,{checksumAddress:e,parameter:n});if(n.type==="address")return A2(r,{checksum:e});if(n.type==="bool")return P2(r);if(n.type.startsWith("uint")||n.type.startsWith("int")){const s=n.type.startsWith("int"),[,,o="256"]=d0.exec(n.type)??[];return T2(r,{signed:s,size:Number(o)})}if(n.type.startsWith("bytes"))return S2(r,{type:n.type});if(n.type==="string")return I2(r);throw new y0(n.type)}function Xu(e){let t=0;for(let s=0;s<e.length;s++){const{dynamic:o,encoded:a}=e[s];o?t+=32:t+=Et(a)}const r=[],n=[];let i=0;for(let s=0;s<e.length;s++){const{dynamic:o,encoded:a}=e[s];o?(r.push(Je(t+i,{size:32})),n.push(a),i+=Et(a)):r.push(a)}return Vt(...r,...n)}function A2(e,t){const{checksum:r=!1}=t;return Ao(e,{strict:r}),{dynamic:!1,encoded:en(e.toLowerCase())}}function _2(e,t){const{checksumAddress:r,length:n,parameter:i}=t,s=n===null;if(!Array.isArray(e))throw new C2(e);if(!s&&e.length!==n)throw new O2({expectedLength:n,givenLength:e.length,type:`${i.type}[${n}]`});let o=!1;const a=[];for(let c=0;c<e.length;c++){const f=Zu({checksumAddress:r,parameter:i,value:e[c]});f.dynamic&&(o=!0),a.push(f)}if(s||o){const c=Xu(a);if(s){const f=Je(a.length,{size:32});return{dynamic:!0,encoded:a.length>0?Vt(f,c):f}}if(o)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:Vt(...a.map(({encoded:c})=>c))}}function S2(e,{type:t}){const[,r]=t.split("bytes"),n=Et(e);if(!r){let i=e;return n%32!==0&&(i=tn(i,Math.ceil((e.length-2)/2/32)*32)),{dynamic:!0,encoded:Vt(en(Je(n,{size:32})),i)}}if(n!==Number.parseInt(r))throw new p0({expectedSize:Number.parseInt(r),value:e});return{dynamic:!1,encoded:tn(e)}}function P2(e){if(typeof e!="boolean")throw new xe(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:en(hh(e))}}function T2(e,{signed:t,size:r}){if(typeof r=="number"){const n=2n**(BigInt(r)-(t?1n:0n))-1n,i=t?-n-1n:0n;if(e>n||e<i)throw new mh({max:n.toString(),min:i.toString(),signed:t,size:r/8,value:e.toString()})}return{dynamic:!1,encoded:Je(e,{size:32,signed:t})}}function I2(e){const t=Du(e),r=Math.ceil(Et(t)/32),n=[];for(let i=0;i<r;i++)n.push(tn(ju(t,i*32,(i+1)*32)));return{dynamic:!0,encoded:Vt(tn(Je(Et(t),{size:32})),...n)}}function k2(e,t){const{checksumAddress:r,parameter:n}=t;let i=!1;const s=[];for(let o=0;o<n.components.length;o++){const a=n.components[o],c=Array.isArray(e)?o:a.name,f=Zu({checksumAddress:r,parameter:a,value:e[c]});s.push(f),f.dynamic&&(i=!0)}return{dynamic:i,encoded:i?Xu(s):Vt(...s.map(({encoded:o})=>o))}}function B2(e){const t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function l0(e,t,r){const{checksumAddress:n=!1}={};if(e.length!==t.length)throw new h0({expectedLength:e.length,givenLength:t.length});const i=x2({checksumAddress:n,parameters:e,values:t}),s=Xu(i);return s.length===0?"0x":s}function Kc(e,t){if(e.length!==t.length)throw new h0({expectedLength:e.length,givenLength:t.length});const r=[];for(let n=0;n<e.length;n++){const i=e[n],s=t[n];r.push(Kc.encode(i,s))}return Vt(...r)}(function(e){function t(r,n,i=!1){if(r==="address"){const c=n;return Ao(c),en(c.toLowerCase(),i?32:0)}if(r==="string")return Du(n);if(r==="bytes")return n;if(r==="bool")return en(hh(n),i?32:1);const s=r.match(d0);if(s){const[c,f,u="256"]=s,d=Number.parseInt(u)/8;return Je(n,{size:i?32:d,signed:f==="int"})}const o=r.match(E2);if(o){const[c,f]=o;if(Number.parseInt(f)!==(n.length-2)/2)throw new p0({expectedSize:Number.parseInt(f),value:n});return tn(n,i?32:0)}const a=r.match(v2);if(a&&Array.isArray(n)){const[c,f]=a,u=[];for(let d=0;d<n.length;d++)u.push(t(f,n[d],!0));return u.length===0?"0x":Vt(...u)}throw new y0(r)}e.encode=t})(Kc||(Kc={}));class O2 extends xe{constructor({expectedLength:t,givenLength:r,type:n}){super(`Array length mismatch for type \`${n}\`. Expected: \`${t}\`. Given: \`${r}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"})}}class p0 extends xe{constructor({expectedSize:t,value:r}){super(`Size of bytes "${r}" (bytes${Et(r)}) does not match expected size (bytes${t}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class h0 extends xe{constructor({expectedLength:t,givenLength:r}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${t}`,`Given length (values): ${r}`].join(`
44
- `)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class C2 extends xe{constructor(t){super(`Value \`${t}\` is not a valid array.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"})}}class y0 extends xe{constructor(t){super(`Type \`${t}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}function R2(e,t){var i;const{bytecode:r,args:n}=t;return Vt(r,(i=e.inputs)!=null&&i.length&&(n!=null&&n.length)?l0(e.inputs,n):"0x")}function N2(e){return u0(e)}function F2(e,...t){const{overloads:r}=e,n=r?$2([e,...r],e.name,{args:t[0]}):e,i=U2(n),s=t.length>0?l0(n.inputs,t[0]):void 0;return s?Vt(i,s):i}function hn(e,t={}){return u0(e,t)}function $2(e,t,r){const n=g2(e,t,r);if(n.type!=="function")throw new Wc({name:t,type:"function"});return n}function U2(e){return f0(e)}const H2="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",$t="0x0000000000000000000000000000000000000000",L2="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033";async function M2(e,t){const{blockNumber:r,blockTag:n,calls:i,stateOverrides:s,traceAssetChanges:o,traceTransfers:a,validation:c}=t,f=t.account?ke(t.account):void 0;if(o&&!f)throw new D("`account` is required when `traceAssetChanges` is true");const u=f?R2(N2("constructor(bytes, bytes)"),{bytecode:Eh,args:[L2,F2(hn("function getBalance(address)"),[f.address])]}):void 0,d=o?await Promise.all(t.calls.map(async M=>{if(!M.data&&!M.abi)return;const{accessList:B}=await qh(e,{account:f.address,...M,data:M.abi?xt(M):M.data});return B.map(({address:q,storageKeys:W})=>W.length>0?q:null)})).then(M=>M.flat().filter(Boolean)):[],y=await zc(e,{blockNumber:r,blockTag:n,blocks:[...o?[{calls:[{data:u}],stateOverrides:s},{calls:d.map((M,B)=>({abi:[hn("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[f.address],to:M,from:$t,nonce:B})),stateOverrides:[{address:$t,nonce:0}]}]:[],{calls:[...i,{}].map(M=>({...M,from:f==null?void 0:f.address})),stateOverrides:s},...o?[{calls:[{data:u}]},{calls:d.map((M,B)=>({abi:[hn("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[f.address],to:M,from:$t,nonce:B})),stateOverrides:[{address:$t,nonce:0}]},{calls:d.map((M,B)=>({to:M,abi:[hn("function decimals() returns (uint256)")],functionName:"decimals",from:$t,nonce:B})),stateOverrides:[{address:$t,nonce:0}]},{calls:d.map((M,B)=>({to:M,abi:[hn("function tokenURI(uint256) returns (string)")],functionName:"tokenURI",args:[0n],from:$t,nonce:B})),stateOverrides:[{address:$t,nonce:0}]},{calls:d.map((M,B)=>({to:M,abi:[hn("function symbol() returns (string)")],functionName:"symbol",from:$t,nonce:B})),stateOverrides:[{address:$t,nonce:0}]}]:[]],traceTransfers:a,validation:c}),p=o?y[2]:y[0],[g,b,,E,A,P,w,_]=o?y:[],{calls:T,...I}=p,R=T.slice(0,-1)??[],L=(g==null?void 0:g.calls)??[],S=(b==null?void 0:b.calls)??[],$=[...L,...S].map(M=>M.status==="success"?Ue(M.data):null),C=(E==null?void 0:E.calls)??[],U=(A==null?void 0:A.calls)??[],j=[...C,...U].map(M=>M.status==="success"?Ue(M.data):null),V=((P==null?void 0:P.calls)??[]).map(M=>M.status==="success"?M.result:null),Y=((_==null?void 0:_.calls)??[]).map(M=>M.status==="success"?M.result:null),X=((w==null?void 0:w.calls)??[]).map(M=>M.status==="success"?M.result:null),J=[];for(const[M,B]of j.entries()){const q=$[M];if(typeof B!="bigint"||typeof q!="bigint")continue;const W=V[M-1],k=Y[M-1],N=X[M-1],H=M===0?{address:H2,decimals:18,symbol:"ETH"}:{address:d[M-1],decimals:N||W?Number(W??1):void 0,symbol:k??void 0};J.some(Z=>Z.token.address===H.address)||J.push({token:H,value:{pre:q,post:B,diff:B-q}})}return{assetChanges:J,block:I,results:R}}class m0 extends pu{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,sg(t);const n=eo(r);if(this.iHash=t.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 i=this.blockLen,s=new Uint8Array(i);s.set(n.length>i?t.create().update(n).digest():n);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=t.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),Or(s)}update(t){return Nn(this),this.iHash.update(t),this}digestInto(t){Nn(this),Bt(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:n,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return t=t,t.finished=i,t.destroyed=s,t.blockLen=o,t.outputLen=a,t.oHash=r._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const g0=(e,t,r)=>new m0(e,t).update(r).digest();g0.create=(e,t)=>new m0(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const nt=BigInt(0),et=BigInt(1),Mr=BigInt(2),D2=BigInt(3),b0=BigInt(4),w0=BigInt(5),v0=BigInt(8);function gt(e,t){const r=e%t;return r>=nt?r:t+r}function pt(e,t,r){let n=e;for(;t-- >nt;)n*=n,n%=r;return n}function fd(e,t){if(e===nt)throw new Error("invert: expected non-zero number");if(t<=nt)throw new Error("invert: expected positive modulus, got "+t);let r=gt(e,t),n=t,i=nt,s=et;for(;r!==nt;){const a=n/r,c=n%r,f=i-s*a;n=r,r=c,i=s,s=f}if(n!==et)throw new Error("invert: does not exist");return gt(i,t)}function E0(e,t){const r=(e.ORDER+et)/b0,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw new Error("Cannot find square root");return n}function j2(e,t){const r=(e.ORDER-w0)/v0,n=e.mul(t,Mr),i=e.pow(n,r),s=e.mul(t,i),o=e.mul(e.mul(s,Mr),i),a=e.mul(s,e.sub(o,e.ONE));if(!e.eql(e.sqr(a),t))throw new Error("Cannot find square root");return a}function z2(e){if(e<BigInt(3))throw new Error("sqrt is not defined for small field");let t=e-et,r=0;for(;t%Mr===nt;)t/=Mr,r++;let n=Mr;const i=_o(e);for(;dd(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return E0;let s=i.pow(n,t);const o=(t+et)/Mr;return function(c,f){if(c.is0(f))return f;if(dd(c,f)!==1)throw new Error("Cannot find square root");let u=r,d=c.mul(c.ONE,s),y=c.pow(f,t),p=c.pow(f,o);for(;!c.eql(y,c.ONE);){if(c.is0(y))return c.ZERO;let g=1,b=c.sqr(y);for(;!c.eql(b,c.ONE);)if(g++,b=c.sqr(b),g===u)throw new Error("Cannot find square root");const E=et<<BigInt(u-g-1),A=c.pow(d,E);u=g,d=c.sqr(A),y=c.mul(y,d),p=c.mul(p,A)}return p}}function q2(e){return e%b0===D2?E0:e%v0===w0?j2:z2(e)}const G2=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function V2(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=G2.reduce((n,i)=>(n[i]="function",n),t);return Lu(e,r),e}function W2(e,t,r){if(r<nt)throw new Error("invalid exponent, negatives unsupported");if(r===nt)return e.ONE;if(r===et)return t;let n=e.ONE,i=t;for(;r>nt;)r&et&&(n=e.mul(n,i)),i=e.sqr(i),r>>=et;return n}function x0(e,t,r=!1){const n=new Array(t.length).fill(r?e.ZERO:void 0),i=t.reduce((o,a,c)=>e.is0(a)?o:(n[c]=o,e.mul(o,a)),e.ONE),s=e.inv(i);return t.reduceRight((o,a,c)=>e.is0(a)?o:(n[c]=e.mul(o,n[c]),e.mul(o,a)),s),n}function dd(e,t){const r=(e.ORDER-et)/Mr,n=e.pow(t,r),i=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),o=e.eql(n,e.neg(e.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function K2(e,t){t!==void 0&&Si(t);const r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function _o(e,t,r=!1,n={}){if(e<=nt)throw new Error("invalid field: expected ORDER > 0, got "+e);let i,s;if(typeof t=="object"&&t!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");const u=t;u.BITS&&(i=u.BITS),u.sqrt&&(s=u.sqrt),typeof u.isLE=="boolean"&&(r=u.isLE)}else typeof t=="number"&&(i=t),n.sqrt&&(s=n.sqrt);const{nBitLength:o,nByteLength:a}=K2(e,i);if(a>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let c;const f=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:a,MASK:ho(o),ZERO:nt,ONE:et,create:u=>gt(u,e),isValid:u=>{if(typeof u!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof u);return nt<=u&&u<e},is0:u=>u===nt,isValidNot0:u=>!f.is0(u)&&f.isValid(u),isOdd:u=>(u&et)===et,neg:u=>gt(-u,e),eql:(u,d)=>u===d,sqr:u=>gt(u*u,e),add:(u,d)=>gt(u+d,e),sub:(u,d)=>gt(u-d,e),mul:(u,d)=>gt(u*d,e),pow:(u,d)=>W2(f,u,d),div:(u,d)=>gt(u*fd(d,e),e),sqrN:u=>u*u,addN:(u,d)=>u+d,subN:(u,d)=>u-d,mulN:(u,d)=>u*d,inv:u=>fd(u,e),sqrt:s||(u=>(c||(c=q2(e)),c(f,u))),toBytes:u=>r?dh(u,a):Hu(u,a),fromBytes:u=>{if(u.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+u.length);return r?fh(u):po(u)},invertBatch:u=>x0(f,u),cmov:(u,d,y)=>y?d:u});return Object.freeze(f)}function A0(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function _0(e){const t=A0(e);return t+Math.ceil(t/2)}function Y2(e,t,r=!1){const n=e.length,i=A0(t),s=_0(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const o=r?fh(e):po(e),a=gt(o,t-et)+et;return r?dh(a,i):Hu(a,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Hn=BigInt(0),Dr=BigInt(1);function mi(e,t){const r=t.negate();return e?r:t}function Z2(e,t,r){const n=o=>o.pz,i=x0(e.Fp,r.map(n));return r.map((o,a)=>o.toAffine(i[a])).map(e.fromAffine)}function S0(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Qo(e,t){S0(e,t);const r=Math.ceil(t/e)+1,n=2**(e-1),i=2**e,s=ho(e),o=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:i,shiftBy:o}}function ld(e,t,r){const{windowSize:n,mask:i,maxNumber:s,shiftBy:o}=r;let a=Number(e&i),c=e>>o;a>n&&(a-=s,c+=Dr);const f=t*n,u=f+Math.abs(a)-1,d=a===0,y=a<0,p=t%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:y,isNegF:p,offsetF:f}}function X2(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function J2(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}const ea=new WeakMap,P0=new WeakMap;function ta(e){return P0.get(e)||1}function pd(e){if(e!==Hn)throw new Error("invalid wNAF")}function Q2(e,t){return{constTimeNegate:mi,hasPrecomputes(r){return ta(r)!==1},unsafeLadder(r,n,i=e.ZERO){let s=r;for(;n>Hn;)n&Dr&&(i=i.add(s)),s=s.double(),n>>=Dr;return i},precomputeWindow(r,n){const{windows:i,windowSize:s}=Qo(n,t),o=[];let a=r,c=a;for(let f=0;f<i;f++){c=a,o.push(c);for(let u=1;u<s;u++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,n,i){let s=e.ZERO,o=e.BASE;const a=Qo(r,t);for(let c=0;c<a.windows;c++){const{nextN:f,offset:u,isZero:d,isNeg:y,isNegF:p,offsetF:g}=ld(i,c,a);i=f,d?o=o.add(mi(p,n[g])):s=s.add(mi(y,n[u]))}return pd(i),{p:s,f:o}},wNAFUnsafe(r,n,i,s=e.ZERO){const o=Qo(r,t);for(let a=0;a<o.windows&&i!==Hn;a++){const{nextN:c,offset:f,isZero:u,isNeg:d}=ld(i,a,o);if(i=c,!u){const y=n[f];s=s.add(d?y.negate():y)}}return pd(i),s},getPrecomputes(r,n,i){let s=ea.get(n);return s||(s=this.precomputeWindow(n,r),r!==1&&(typeof i=="function"&&(s=i(s)),ea.set(n,s))),s},wNAFCached(r,n,i){const s=ta(r);return this.wNAF(s,this.getPrecomputes(s,r,i),n)},wNAFCachedUnsafe(r,n,i,s){const o=ta(r);return o===1?this.unsafeLadder(r,n,s):this.wNAFUnsafe(o,this.getPrecomputes(o,r,i),n,s)},setWindowSize(r,n){S0(n,t),P0.set(r,n),ea.delete(r)}}}function ev(e,t,r,n){let i=t,s=e.ZERO,o=e.ZERO;for(;r>Hn||n>Hn;)r&Dr&&(s=s.add(i)),n&Dr&&(o=o.add(i)),i=i.double(),r>>=Dr,n>>=Dr;return{p1:s,p2:o}}function tv(e,t,r,n){X2(r,e),J2(n,t);const i=r.length,s=n.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=Zb(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const f=ho(c),u=new Array(Number(f)+1).fill(o),d=Math.floor((t.BITS-1)/c)*c;let y=o;for(let p=d;p>=0;p-=c){u.fill(o);for(let b=0;b<s;b++){const E=n[b],A=Number(E>>BigInt(p)&f);u[A]=u[A].add(r[b])}let g=o;for(let b=u.length-1,E=o;b>0;b--)E=E.add(u[b]),g=g.add(E);if(y=y.add(g),p!==0)for(let b=0;b<c;b++)y=y.double()}return y}function hd(e,t){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return V2(t),t}else return _o(e)}function rv(e,t,r={}){if(!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(const a of["p","n","h"]){const c=t[a];if(!(typeof c=="bigint"&&c>Hn))throw new Error(`CURVE.${a} must be positive bigint`)}const n=hd(t.p,r.Fp),i=hd(t.n,r.Fn),o=["Gx","Gy","a","b"];for(const a of o)if(!n.isValid(t[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return{Fp:n,Fn:i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function yd(e){e.lowS!==void 0&&Ws("lowS",e.lowS),e.prehash!==void 0&&Ws("prehash",e.prehash)}class nv extends Error{constructor(t=""){super(t)}}const nr={Err:nv,_tlv:{encode:(e,t)=>{const{Err:r}=nr;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");const n=t.length/2,i=gs(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?gs(i.length/2|128):"";return gs(e)+s+i+t},decode(e,t){const{Err:r}=nr;let n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");const i=t[n++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&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 f=t.subarray(n,n+c);if(f.length!==c)throw new r("tlv.decode: length bytes not complete");if(f[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const u of f)o=o<<8|u;if(n+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=t.subarray(n,n+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+o)}}},_int:{encode(e){const{Err:t}=nr;if(e<gi)throw new t("integer: negative integers are not allowed");let r=gs(e);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){const{Err:t}=nr;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return po(e)}},toSig(e){const{Err:t,_int:r,_tlv:n}=nr,i=yt("signature",e),{v:s,l:o}=n.decode(48,i);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,s),{v:f,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(f)}},hexFromSig(e){const{_tlv:t,_int:r}=nr,n=t.encode(2,r.encode(e.r)),i=t.encode(2,r.encode(e.s)),s=n+i;return t.encode(48,s)}},gi=BigInt(0),bi=BigInt(1),iv=BigInt(2),As=BigInt(3),sv=BigInt(4);function ov(e,t,r){function n(i){const s=e.sqr(i),o=e.mul(s,i);return e.add(e.add(o,e.mul(i,t)),r)}return n}function T0(e,t,r){const{BYTES:n}=e;function i(s){let o;if(typeof s=="bigint")o=s;else{let a=yt("private key",s);if(t){if(!t.includes(a.length*2))throw new Error("invalid private key");const c=new Uint8Array(n);c.set(a,c.length-a.length),a=c}try{o=e.fromBytes(a)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof s}`)}}if(r&&(o=e.create(o)),!e.isValidNot0(o))throw new Error("invalid private key: out of range [1..N-1]");return o}return i}function av(e,t={}){const{Fp:r,Fn:n}=rv("weierstrass",e,t),{h:i,n:s}=e;Lu(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:o}=t;if(o&&(!r.is0(e.a)||typeof o.beta!="bigint"||typeof o.splitScalar!="function"))throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');function a(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function c(L,S,$){const{x:C,y:U}=S.toAffine(),j=r.toBytes(C);if(Ws("isCompressed",$),$){a();const V=!r.isOdd(U);return Hr(I0(V),j)}else return Hr(Uint8Array.of(4),j,r.toBytes(U))}function f(L){Bt(L);const S=r.BYTES,$=S+1,C=2*S+1,U=L.length,j=L[0],V=L.subarray(1);if(U===$&&(j===2||j===3)){const Y=r.fromBytes(V);if(!r.isValid(Y))throw new Error("bad point: is not on curve, wrong x");const X=y(Y);let J;try{J=r.sqrt(X)}catch(q){const W=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+W)}a();const M=r.isOdd(J);return(j&1)===1!==M&&(J=r.neg(J)),{x:Y,y:J}}else if(U===C&&j===4){const Y=r.fromBytes(V.subarray(S*0,S*1)),X=r.fromBytes(V.subarray(S*1,S*2));if(!p(Y,X))throw new Error("bad point: is not on curve");return{x:Y,y:X}}else throw new Error(`bad point: got length ${U}, expected compressed=${$} or uncompressed=${C}`)}const u=t.toBytes||c,d=t.fromBytes||f,y=ov(r,e.a,e.b);function p(L,S){const $=r.sqr(S),C=y(L);return r.eql($,C)}if(!p(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const g=r.mul(r.pow(e.a,As),sv),b=r.mul(r.sqr(e.b),BigInt(27));if(r.is0(r.add(g,b)))throw new Error("bad curve params: a or b");function E(L,S,$=!1){if(!r.isValid(S)||$&&r.is0(S))throw new Error(`bad point coordinate ${L}`);return S}function A(L){if(!(L instanceof T))throw new Error("ProjectivePoint expected")}const P=Kf((L,S)=>{const{px:$,py:C,pz:U}=L;if(r.eql(U,r.ONE))return{x:$,y:C};const j=L.is0();S==null&&(S=j?r.ONE:r.inv(U));const V=r.mul($,S),Y=r.mul(C,S),X=r.mul(U,S);if(j)return{x:r.ZERO,y:r.ZERO};if(!r.eql(X,r.ONE))throw new Error("invZ was invalid");return{x:V,y:Y}}),w=Kf(L=>{if(L.is0()){if(t.allowInfinityPoint&&!r.is0(L.py))return;throw new Error("bad point: ZERO")}const{x:S,y:$}=L.toAffine();if(!r.isValid(S)||!r.isValid($))throw new Error("bad point: x or y not field elements");if(!p(S,$))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function _(L,S,$,C,U){return $=new T(r.mul($.px,L),$.py,$.pz),S=mi(C,S),$=mi(U,$),S.add($)}class T{constructor(S,$,C){this.px=E("x",S),this.py=E("y",$,!0),this.pz=E("z",C),Object.freeze(this)}static fromAffine(S){const{x:$,y:C}=S||{};if(!S||!r.isValid($)||!r.isValid(C))throw new Error("invalid affine point");if(S instanceof T)throw new Error("projective point not allowed");return r.is0($)&&r.is0(C)?T.ZERO:new T($,C,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(S){return Z2(T,"pz",S)}static fromBytes(S){return Bt(S),T.fromHex(S)}static fromHex(S){const $=T.fromAffine(d(yt("pointHex",S)));return $.assertValidity(),$}static fromPrivateKey(S){const $=T0(n,t.allowedPrivateKeyLengths,t.wrapPrivateKey);return T.BASE.multiply($(S))}static msm(S,$){return tv(T,n,S,$)}precompute(S=8,$=!0){return R.setWindowSize(this,S),$||this.multiply(As),this}_setWindowSize(S){this.precompute(S)}assertValidity(){w(this)}hasEvenY(){const{y:S}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(S)}equals(S){A(S);const{px:$,py:C,pz:U}=this,{px:j,py:V,pz:Y}=S,X=r.eql(r.mul($,Y),r.mul(j,U)),J=r.eql(r.mul(C,Y),r.mul(V,U));return X&&J}negate(){return new T(this.px,r.neg(this.py),this.pz)}double(){const{a:S,b:$}=e,C=r.mul($,As),{px:U,py:j,pz:V}=this;let Y=r.ZERO,X=r.ZERO,J=r.ZERO,M=r.mul(U,U),B=r.mul(j,j),q=r.mul(V,V),W=r.mul(U,j);return W=r.add(W,W),J=r.mul(U,V),J=r.add(J,J),Y=r.mul(S,J),X=r.mul(C,q),X=r.add(Y,X),Y=r.sub(B,X),X=r.add(B,X),X=r.mul(Y,X),Y=r.mul(W,Y),J=r.mul(C,J),q=r.mul(S,q),W=r.sub(M,q),W=r.mul(S,W),W=r.add(W,J),J=r.add(M,M),M=r.add(J,M),M=r.add(M,q),M=r.mul(M,W),X=r.add(X,M),q=r.mul(j,V),q=r.add(q,q),M=r.mul(q,W),Y=r.sub(Y,M),J=r.mul(q,B),J=r.add(J,J),J=r.add(J,J),new T(Y,X,J)}add(S){A(S);const{px:$,py:C,pz:U}=this,{px:j,py:V,pz:Y}=S;let X=r.ZERO,J=r.ZERO,M=r.ZERO;const B=e.a,q=r.mul(e.b,As);let W=r.mul($,j),k=r.mul(C,V),N=r.mul(U,Y),H=r.add($,C),Z=r.add(j,V);H=r.mul(H,Z),Z=r.add(W,k),H=r.sub(H,Z),Z=r.add($,U);let Q=r.add(j,Y);return Z=r.mul(Z,Q),Q=r.add(W,N),Z=r.sub(Z,Q),Q=r.add(C,U),X=r.add(V,Y),Q=r.mul(Q,X),X=r.add(k,N),Q=r.sub(Q,X),M=r.mul(B,Z),X=r.mul(q,N),M=r.add(X,M),X=r.sub(k,M),M=r.add(k,M),J=r.mul(X,M),k=r.add(W,W),k=r.add(k,W),N=r.mul(B,N),Z=r.mul(q,Z),k=r.add(k,N),N=r.sub(W,N),N=r.mul(B,N),Z=r.add(Z,N),W=r.mul(k,Z),J=r.add(J,W),W=r.mul(Q,Z),X=r.mul(H,X),X=r.sub(X,W),W=r.mul(H,k),M=r.mul(Q,M),M=r.add(M,W),new T(X,J,M)}subtract(S){return this.add(S.negate())}is0(){return this.equals(T.ZERO)}multiply(S){const{endo:$}=t;if(!n.isValidNot0(S))throw new Error("invalid scalar: out of range");let C,U;const j=V=>R.wNAFCached(this,V,T.normalizeZ);if($){const{k1neg:V,k1:Y,k2neg:X,k2:J}=$.splitScalar(S),{p:M,f:B}=j(Y),{p:q,f:W}=j(J);U=B.add(W),C=_($.beta,M,q,V,X)}else{const{p:V,f:Y}=j(S);C=V,U=Y}return T.normalizeZ([C,U])[0]}multiplyUnsafe(S){const{endo:$}=t,C=this;if(!n.isValid(S))throw new Error("invalid scalar: out of range");if(S===gi||C.is0())return T.ZERO;if(S===bi)return C;if(R.hasPrecomputes(this))return this.multiply(S);if($){const{k1neg:U,k1:j,k2neg:V,k2:Y}=$.splitScalar(S),{p1:X,p2:J}=ev(T,C,j,Y);return _($.beta,X,J,U,V)}else return R.wNAFCachedUnsafe(C,S)}multiplyAndAddUnsafe(S,$,C){const U=this.multiplyUnsafe($).add(S.multiplyUnsafe(C));return U.is0()?void 0:U}toAffine(S){return P(this,S)}isTorsionFree(){const{isTorsionFree:S}=t;return i===bi?!0:S?S(T,this):R.wNAFCachedUnsafe(this,s).is0()}clearCofactor(){const{clearCofactor:S}=t;return i===bi?this:S?S(T,this):this.multiplyUnsafe(i)}toBytes(S=!0){return Ws("isCompressed",S),this.assertValidity(),u(T,this,S)}toRawBytes(S=!0){return this.toBytes(S)}toHex(S=!0){return Pi(this.toBytes(S))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}T.BASE=new T(e.Gx,e.Gy,r.ONE),T.ZERO=new T(r.ZERO,r.ONE,r.ZERO),T.Fp=r,T.Fn=n;const I=n.BITS,R=Q2(T,t.endo?Math.ceil(I/2):I);return T}function I0(e){return Uint8Array.of(e?2:3)}function cv(e,t,r={}){Lu(t,{hash:"function"},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=t.randomBytes||lg,i=t.hmac||((C,...U)=>g0(t.hash,C,Hr(...U))),{Fp:s,Fn:o}=e,{ORDER:a,BITS:c}=o;function f(C){const U=a>>bi;return C>U}function u(C){return f(C)?o.neg(C):C}function d(C,U){if(!o.isValidNot0(U))throw new Error(`invalid signature ${C}: out of range 1..CURVE.n`)}class y{constructor(U,j,V){d("r",U),d("s",j),this.r=U,this.s=j,V!=null&&(this.recovery=V),Object.freeze(this)}static fromCompact(U){const j=o.BYTES,V=yt("compactSignature",U,j*2);return new y(o.fromBytes(V.subarray(0,j)),o.fromBytes(V.subarray(j,j*2)))}static fromDER(U){const{r:j,s:V}=nr.toSig(yt("DER",U));return new y(j,V)}assertValidity(){}addRecoveryBit(U){return new y(this.r,this.s,U)}recoverPublicKey(U){const j=s.ORDER,{r:V,s:Y,recovery:X}=this;if(X==null||![0,1,2,3].includes(X))throw new Error("recovery id invalid");if(a*iv<j&&X>1)throw new Error("recovery id is ambiguous for h>1 curve");const M=X===2||X===3?V+a:V;if(!s.isValid(M))throw new Error("recovery id 2 or 3 invalid");const B=s.toBytes(M),q=e.fromHex(Hr(I0((X&1)===0),B)),W=o.inv(M),k=w(yt("msgHash",U)),N=o.create(-k*W),H=o.create(Y*W),Z=e.BASE.multiplyUnsafe(N).add(q.multiplyUnsafe(H));if(Z.is0())throw new Error("point at infinify");return Z.assertValidity(),Z}hasHighS(){return f(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,o.neg(this.s),this.recovery):this}toBytes(U){if(U==="compact")return Hr(o.toBytes(this.r),o.toBytes(this.s));if(U==="der")return lu(nr.hexFromSig(this));throw new Error("invalid format")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Pi(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Pi(this.toBytes("compact"))}}const p=T0(o,r.allowedPrivateKeyLengths,r.wrapPrivateKey),g={isValidPrivateKey(C){try{return p(C),!0}catch{return!1}},normPrivateKeyToScalar:p,randomPrivateKey:()=>{const C=a;return Y2(n(_0(C)),C)},precompute(C=8,U=e.BASE){return U.precompute(C,!1)}};function b(C,U=!0){return e.fromPrivateKey(C).toBytes(U)}function E(C){if(typeof C=="bigint")return!1;if(C instanceof e)return!0;const j=yt("key",C).length,V=s.BYTES,Y=V+1,X=2*V+1;if(!(r.allowedPrivateKeyLengths||o.BYTES===Y))return j===Y||j===X}function A(C,U,j=!0){if(E(C)===!0)throw new Error("first arg must be private key");if(E(U)===!1)throw new Error("second arg must be public key");return e.fromHex(U).multiply(p(C)).toBytes(j)}const P=t.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");const U=po(C),j=C.length*8-c;return j>0?U>>BigInt(j):U},w=t.bits2int_modN||function(C){return o.create(P(C))},_=ho(c);function T(C){return Yb("num < 2^"+c,C,gi,_),o.toBytes(C)}function I(C,U,j=R){if(["recovered","canonical"].some(H=>H in j))throw new Error("sign() legacy options not supported");const{hash:V}=t;let{lowS:Y,prehash:X,extraEntropy:J}=j;Y==null&&(Y=!0),C=yt("msgHash",C),yd(j),X&&(C=yt("prehashed msgHash",V(C)));const M=w(C),B=p(U),q=[T(B),T(M)];if(J!=null&&J!==!1){const H=J===!0?n(s.BYTES):J;q.push(yt("extraEntropy",H))}const W=Hr(...q),k=M;function N(H){const Z=P(H);if(!o.isValidNot0(Z))return;const Q=o.inv(Z),ie=e.BASE.multiply(Z).toAffine(),ne=o.create(ie.x);if(ne===gi)return;const re=o.create(Q*o.create(k+ne*B));if(re===gi)return;let te=(ie.x===ne?0:2)|Number(ie.y&bi),se=re;return Y&&f(re)&&(se=u(re),te^=1),new y(ne,se,te)}return{seed:W,k2sig:N}}const R={lowS:t.lowS,prehash:!1},L={lowS:t.lowS,prehash:!1};function S(C,U,j=R){const{seed:V,k2sig:Y}=I(C,U,j);return Xb(t.hash.outputLen,o.BYTES,i)(V,Y)}e.BASE.precompute(8);function $(C,U,j,V=L){const Y=C;U=yt("msgHash",U),j=yt("publicKey",j),yd(V);const{lowS:X,prehash:J,format:M}=V;if("strict"in V)throw new Error("options.strict was renamed to lowS");if(M!==void 0&&!["compact","der","js"].includes(M))throw new Error('format must be "compact", "der" or "js"');const B=typeof Y=="string"||du(Y),q=!B&&!M&&typeof Y=="object"&&Y!==null&&typeof Y.r=="bigint"&&typeof Y.s=="bigint";if(!B&&!q)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let W,k;try{if(q)if(M===void 0||M==="js")W=new y(Y.r,Y.s);else throw new Error("invalid format");if(B){try{M!=="compact"&&(W=y.fromDER(Y))}catch(se){if(!(se instanceof nr.Err))throw se}!W&&M!=="der"&&(W=y.fromCompact(Y))}k=e.fromHex(j)}catch{return!1}if(!W||X&&W.hasHighS())return!1;J&&(U=t.hash(U));const{r:N,s:H}=W,Z=w(U),Q=o.inv(H),ie=o.create(Z*Q),ne=o.create(N*Q),re=e.BASE.multiplyUnsafe(ie).add(k.multiplyUnsafe(ne));return re.is0()?!1:o.create(re.x)===N}return Object.freeze({getPublicKey:b,getSharedSecret:A,sign:S,verify:$,utils:g,Point:e,Signature:y})}function uv(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=_o(t.n,e.nBitLength),i={Fp:r,Fn:n,allowedPrivateKeyLengths:e.allowedPrivateKeyLengths,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,wrapPrivateKey:e.wrapPrivateKey,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:i}}function fv(e){const{CURVE:t,curveOpts:r}=uv(e),n={hash:e.hash,hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:r,ecdsaOpts:n}}function dv(e,t){return Object.assign({},t,{ProjectivePoint:t.Point,CURVE:e})}function lv(e){const{CURVE:t,curveOpts:r,ecdsaOpts:n}=fv(e),i=av(t,r),s=cv(i,n,r);return dv(e,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function pv(e,t){const r=n=>lv({...e,hash:n});return{...r(t),create:r}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ks={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")};BigInt(0);const hv=BigInt(1),Yc=BigInt(2),md=(e,t)=>(e+t/Yc)/t;function yv(e){const t=Ks.p,r=BigInt(3),n=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),f=e*e*e%t,u=f*f*e%t,d=pt(u,r,t)*u%t,y=pt(d,r,t)*u%t,p=pt(y,Yc,t)*f%t,g=pt(p,i,t)*p%t,b=pt(g,s,t)*g%t,E=pt(b,a,t)*b%t,A=pt(E,c,t)*E%t,P=pt(A,a,t)*b%t,w=pt(P,r,t)*u%t,_=pt(w,o,t)*g%t,T=pt(_,n,t)*f%t,I=pt(T,Yc,t);if(!Zc.eql(Zc.sqr(I),e))throw new Error("Cannot find square root");return I}const Zc=_o(Ks.p,void 0,void 0,{sqrt:yv}),k0=pv({...Ks,Fp:Zc,lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=Ks.n,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-hv*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,o=BigInt("0x100000000000000000000000000000000"),a=md(s*e,t),c=md(-n*e,t);let f=gt(e-a*r-c*i,t),u=gt(-a*n-c*s,t);const d=f>o,y=u>o;if(d&&(f=t-f),y&&(u=t-u),f>o||u>o)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:d,k1:f,k2neg:y,k2:u}}}},Xp),mv=Object.freeze(Object.defineProperty({__proto__:null,secp256k1:k0},Symbol.toStringTag,{value:"Module"}));function gv({r:e,s:t,to:r="hex",v:n,yParity:i}){const s=(()=>{if(i===0||i===1)return i;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 k0.Signature(Ue(e),Ue(t)).toCompactHex()}${s===0?"1b":"1c"}`;return r==="hex"?o:kt(o)}async function Ju(e,t){var d,y,p;const{address:r,factory:n,factoryData:i,hash:s,signature:o,universalSignatureVerifierAddress:a=(p=(y=(d=e.chain)==null?void 0:d.contracts)==null?void 0:y.universalSignatureVerifier)==null?void 0:p.address,...c}=t,f=It(o)?o:typeof o=="object"&&"r"in o&&"s"in o?gv(o):Ce(o),u=await(async()=>!n&&!i||n2(f)?f:i2({address:n,data:i,signature:f}))();try{const g=a?{to:a,data:xt({abi:td,functionName:"isValidSig",args:[r,s,u]}),...c}:{data:mo({abi:td,args:[r,s,u],bytecode:_w}),...c},{data:b}=await ee(e,os,"call")(g);return Wm(b??"0x0")}catch(g){try{if(ss(Tp(r),await jp({hash:s,signature:o})))return!0}catch{}if(g instanceof Dp)return!1;throw g}}async function bv(e,{address:t,message:r,factory:n,factoryData:i,signature:s,...o}){const a=s0(r);return Ju(e,{address:t,factory:n,factoryData:i,hash:a,signature:s,...o})}async function wv(e,t){const{address:r,factory:n,factoryData:i,signature:s,message:o,primaryType:a,types:c,domain:f,...u}=t,d=I1({message:o,primaryType:a,types:c,domain:f});return Ju(e,{address:r,factory:n,factoryData:i,hash:d,signature:s,...u})}function B0(e,{emitOnBegin:t=!1,emitMissed:r=!1,onBlockNumber:n,onError:i,poll:s,pollingInterval:o=e.pollingInterval}){const a=typeof s<"u"?s:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"));let c;return a?(()=>{const d=Oe(["watchBlockNumber",e.uid,t,r,o]);return ur(d,{onBlockNumber:n,onError:i},y=>Jn(async()=>{var p;try{const g=await ee(e,as,"getBlockNumber")({cacheTime:0});if(c){if(g===c)return;if(g-c>1&&r)for(let b=c+1n;b<g;b++)y.onBlockNumber(b,c),c=b}(!c||g>c)&&(y.onBlockNumber(g,c),c=g)}catch(g){(p=y.onError)==null||p.call(y,g)}},{emitOnBegin:t,interval:o}))})():(()=>{const d=Oe(["watchBlockNumber",e.uid,t,r]);return ur(d,{onBlockNumber:n,onError:i},y=>{let p=!0,g=()=>p=!1;return(async()=>{try{const b=(()=>{if(e.transport.type==="fallback"){const A=e.transport.transports.find(P=>P.config.type==="webSocket"||P.config.type==="ipc");return A?A.value:e.transport}return e.transport})(),{unsubscribe:E}=await b.subscribe({params:["newHeads"],onData(A){var w;if(!p)return;const P=Ue((w=A.result)==null?void 0:w.number);y.onBlockNumber(P,c),c=P},onError(A){var P;(P=y.onError)==null||P.call(y,A)}});g=E,p||g()}catch(b){i==null||i(b)}})(),()=>g()})})()}async function vv(e,{confirmations:t=1,hash:r,onReplaced:n,pollingInterval:i=e.pollingInterval,retryCount:s=6,retryDelay:o=({count:c})=>~~(1<<c)*200,timeout:a=18e4}){const c=Oe(["waitForTransactionReceipt",e.uid,r]);let f,u,d,y=!1,p,g;const{promise:b,resolve:E,reject:A}=zu(),P=a?setTimeout(()=>{g(),p(),A(new ab({hash:r}))},a):void 0;return p=ur(c,{onReplaced:n,resolve:E,reject:A},w=>{g=ee(e,B0,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:i,async onBlockNumber(_){const T=R=>{clearTimeout(P),g(),R(),p()};let I=_;if(!y)try{if(d){if(t>1&&(!d.blockNumber||I-d.blockNumber+1n<t))return;T(()=>w.resolve(d));return}if(f||(y=!0,await Dc(async()=>{f=await ee(e,Yu,"getTransaction")({hash:r}),f.blockNumber&&(I=f.blockNumber)},{delay:o,retryCount:s}),y=!1),d=await ee(e,jc,"getTransactionReceipt")({hash:r}),t>1&&(!d.blockNumber||I-d.blockNumber+1n<t))return;T(()=>w.resolve(d))}catch(R){if(R instanceof Lp||R instanceof Mp){if(!f){y=!1;return}try{u=f,y=!0;const L=await Dc(()=>ee(e,Gt,"getBlock")({blockNumber:I,includeTransactions:!0}),{delay:o,retryCount:s,shouldRetry:({error:C})=>C instanceof Vp});y=!1;const S=L.transactions.find(({from:C,nonce:U})=>C===u.from&&U===u.nonce);if(!S||(d=await ee(e,jc,"getTransactionReceipt")({hash:S.hash}),t>1&&(!d.blockNumber||I-d.blockNumber+1n<t)))return;let $="replaced";S.to===u.to&&S.value===u.value&&S.input===u.input?$="repriced":S.from===S.to&&S.value===0n&&($="cancelled"),T(()=>{var C;(C=w.onReplaced)==null||C.call(w,{reason:$,replacedTransaction:u,transaction:S,transactionReceipt:d}),w.resolve(d)})}catch(L){T(()=>w.reject(L))}}else T(()=>w.reject(R))}}})}),b}function Ev(e,{blockTag:t="latest",emitMissed:r=!1,emitOnBegin:n=!1,onBlock:i,onError:s,includeTransactions:o,poll:a,pollingInterval:c=e.pollingInterval}){const f=typeof a<"u"?a:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")),u=o??!1;let d;return f?(()=>{const g=Oe(["watchBlocks",e.uid,t,r,n,u,c]);return ur(g,{onBlock:i,onError:s},b=>Jn(async()=>{var E;try{const A=await ee(e,Gt,"getBlock")({blockTag:t,includeTransactions:u});if(A.number!==null&&(d==null?void 0:d.number)!=null){if(A.number===d.number)return;if(A.number-d.number>1&&r)for(let P=(d==null?void 0:d.number)+1n;P<A.number;P++){const w=await ee(e,Gt,"getBlock")({blockNumber:P,includeTransactions:u});b.onBlock(w,d),d=w}}((d==null?void 0:d.number)==null||t==="pending"&&(A==null?void 0:A.number)==null||A.number!==null&&A.number>d.number)&&(b.onBlock(A,d),d=A)}catch(A){(E=b.onError)==null||E.call(b,A)}},{emitOnBegin:n,interval:c}))})():(()=>{let g=!0,b=!0,E=()=>g=!1;return(async()=>{try{n&&ee(e,Gt,"getBlock")({blockTag:t,includeTransactions:u}).then(w=>{g&&b&&(i(w,void 0),b=!1)}).catch(s);const A=(()=>{if(e.transport.type==="fallback"){const w=e.transport.transports.find(_=>_.config.type==="webSocket"||_.config.type==="ipc");return w?w.value:e.transport}return e.transport})(),{unsubscribe:P}=await A.subscribe({params:["newHeads"],async onData(w){var T;if(!g)return;const _=await ee(e,Gt,"getBlock")({blockNumber:(T=w.result)==null?void 0:T.number,includeTransactions:u}).catch(()=>{});g&&(i(_,d),b=!1,d=_)},onError(w){s==null||s(w)}});E=P,g||E()}catch(A){s==null||s(A)}})(),()=>E()})()}function xv(e,{address:t,args:r,batch:n=!0,event:i,events:s,fromBlock:o,onError:a,onLogs:c,poll:f,pollingInterval:u=e.pollingInterval,strict:d}){const y=typeof f<"u"?f:typeof o=="bigint"?!0:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")),p=d??!1;return y?(()=>{const E=Oe(["watchEvent",t,r,n,e.uid,i,u,o]);return ur(E,{onLogs:c,onError:a},A=>{let P;o!==void 0&&(P=o-1n);let w,_=!1;const T=Jn(async()=>{var I;if(!_){try{w=await ee(e,Gh,"createEventFilter")({address:t,args:r,event:i,events:s,strict:p,fromBlock:o})}catch{}_=!0;return}try{let R;if(w)R=await ee(e,go,"getFilterChanges")({filter:w});else{const L=await ee(e,as,"getBlockNumber")({});P&&P!==L?R=await ee(e,Fu,"getLogs")({address:t,args:r,event:i,events:s,fromBlock:P+1n,toBlock:L}):R=[],P=L}if(R.length===0)return;if(n)A.onLogs(R);else for(const L of R)A.onLogs([L])}catch(R){w&&R instanceof Xr&&(_=!1),(I=A.onError)==null||I.call(A,R)}},{emitOnBegin:!0,interval:u});return async()=>{w&&await ee(e,bo,"uninstallFilter")({filter:w}),T()}})})():(()=>{let E=!0,A=()=>E=!1;return(async()=>{try{const P=(()=>{if(e.transport.type==="fallback"){const I=e.transport.transports.find(R=>R.config.type==="webSocket"||R.config.type==="ipc");return I?I.value:e.transport}return e.transport})(),w=s??(i?[i]:void 0);let _=[];w&&(_=[w.flatMap(R=>ts({abi:[R],eventName:R.name,args:r}))],i&&(_=_[0]));const{unsubscribe:T}=await P.subscribe({params:["logs",{address:t,topics:_}],onData(I){var L;if(!E)return;const R=I.result;try{const{eventName:S,args:$}=Ru({abi:w??[],data:R.data,topics:R.topics,strict:p}),C=cr(R,{args:$,eventName:S});c([C])}catch(S){let $,C;if(S instanceof _i||S instanceof Qs){if(d)return;$=S.abiItem.name,C=(L=S.abiItem.inputs)==null?void 0:L.some(j=>!("name"in j&&j.name))}const U=cr(R,{args:C?[]:{},eventName:$});c([U])}},onError(I){a==null||a(I)}});A=T,E||A()}catch(P){a==null||a(P)}})(),()=>A()})()}function Av(e,{batch:t=!0,onError:r,onTransactions:n,poll:i,pollingInterval:s=e.pollingInterval}){return(typeof i<"u"?i:e.transport.type!=="webSocket"&&e.transport.type!=="ipc")?(()=>{const f=Oe(["watchPendingTransactions",e.uid,t,s]);return ur(f,{onTransactions:n,onError:r},u=>{let d;const y=Jn(async()=>{var p;try{if(!d)try{d=await ee(e,Vh,"createPendingTransactionFilter")({});return}catch(b){throw y(),b}const g=await ee(e,go,"getFilterChanges")({filter:d});if(g.length===0)return;if(t)u.onTransactions(g);else for(const b of g)u.onTransactions([b])}catch(g){(p=u.onError)==null||p.call(u,g)}},{emitOnBegin:!0,interval:s});return async()=>{d&&await ee(e,bo,"uninstallFilter")({filter:d}),y()}})})():(()=>{let f=!0,u=()=>f=!1;return(async()=>{try{const{unsubscribe:d}=await e.transport.subscribe({params:["newPendingTransactions"],onData(y){if(!f)return;const p=y.result;n([p])},onError(y){r==null||r(y)}});u=d,f||u()}catch(d){r==null||r(d)}})(),()=>u()})()}function _v(e){var d,y,p;const{scheme:t,statement:r,...n}=((d=e.match(Sv))==null?void 0:d.groups)??{},{chainId:i,expirationTime:s,issuedAt:o,notBefore:a,requestId:c,...f}=((y=e.match(Pv))==null?void 0:y.groups)??{},u=(p=e.split("Resources:")[1])==null?void 0:p.split(`
45
- - `).slice(1);return{...n,...f,...i?{chainId:Number(i)}:{},...s?{expirationTime:new Date(s)}:{},...o?{issuedAt:new Date(o)}:{},...a?{notBefore:new Date(a)}:{},...c?{requestId:c}:{},...u?{resources:u}:{},...t?{scheme:t}:{},...r?{statement:r}:{}}}const Sv=/^(?:(?<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)?/,Pv=/(?: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 Tv(e){const{address:t,domain:r,message:n,nonce:i,scheme:s,time:o=new Date}=e;if(r&&n.domain!==r||i&&n.nonce!==i||s&&n.scheme!==s||n.expirationTime&&o>=n.expirationTime||n.notBefore&&o<n.notBefore)return!1;try{if(!n.address||!Fe(n.address,{strict:!1})||t&&!ss(n.address,t))return!1}catch{return!1}return!0}async function Iv(e,t){const{address:r,domain:n,message:i,nonce:s,scheme:o,signature:a,time:c=new Date,...f}=t,u=_v(i);if(!u.address||!Tv({address:r,domain:n,message:u,nonce:s,scheme:o,time:c}))return!1;const y=s0(i);return Ju(e,{address:u.address,hash:y,signature:a,...f})}function kv(e){return{call:t=>os(e,t),createAccessList:t=>qh(e,t),createBlockFilter:()=>m1(e),createContractEventFilter:t=>bu(e,t),createEventFilter:t=>Gh(e,t),createPendingTransactionFilter:()=>Vh(e),estimateContractGas:t=>ch(e,t),estimateGas:t=>Cu(e,t),getBalance:t=>ah(e,t),getBlobBaseFee:()=>g1(e),getBlock:t=>Gt(e,t),getBlockNumber:t=>as(e,t),getBlockTransactionCount:t=>b1(e,t),getBytecode:t=>ad(e,t),getChainId:()=>Zn(e),getCode:t=>ad(e,t),getContractEvents:t=>$u(e,t),getEip712Domain:t=>v1(e,t),getEnsAddress:t=>e1(e,t),getEnsAvatar:t=>p1(e,t),getEnsName:t=>h1(e,t),getEnsResolver:t=>y1(e,t),getEnsText:t=>zh(e,t),getFeeHistory:t=>A1(e,t),estimateFeesPerGas:t=>Ob(e,t),getFilterChanges:t=>go(e,t),getFilterLogs:t=>_1(e,t),getGasPrice:()=>Pu(e),getLogs:t=>Fu(e,t),getProof:t=>a2(e,t),estimateMaxPriorityFeePerGas:t=>Bb(e,t),getStorageAt:t=>c2(e,t),getTransaction:t=>Yu(e,t),getTransactionConfirmations:t=>u2(e,t),getTransactionCount:t=>Tu(e,t),getTransactionReceipt:t=>jc(e,t),multicall:t=>f2(e,t),prepareTransactionRequest:t=>lo(e,t),readContract:t=>Wt(e,t),sendRawTransaction:t=>qu(e,t),simulate:t=>zc(e,t),simulateBlocks:t=>zc(e,t),simulateCalls:t=>M2(e,t),simulateContract:t=>Sh(e,t),verifyMessage:t=>bv(e,t),verifySiweMessage:t=>Iv(e,t),verifyTypedData:t=>wv(e,t),uninstallFilter:t=>bo(e,t),waitForTransactionReceipt:t=>vv(e,t),watchBlocks:t=>Ev(e,t),watchBlockNumber:t=>B0(e,t),watchContractEvent:t=>Ph(e,t),watchEvent:t=>xv(e,t),watchPendingTransactions:t=>Av(e,t)}}function Bv(e){const{key:t="public",name:r="Public Client"}=e;return $h({...e,key:t,name:r,type:"publicClient"}).extend(kv)}async function Ov(e,{chain:t}){const{id:r,name:n,nativeCurrency:i,rpcUrls:s,blockExplorers:o}=t;await e.request({method:"wallet_addEthereumChain",params:[{chainId:K(r),chainName:n,nativeCurrency:i,rpcUrls:s.default.http,blockExplorerUrls:o?Object.values(o).map(({url:a})=>a):void 0}]},{dedupe:!0,retryCount:0})}function Cv(e,t){const{abi:r,args:n,bytecode:i,...s}=t,o=mo({abi:r,args:n,bytecode:i});return wo(e,{...s,...s.authorizationList?{to:null}:{},data:o})}async function Rv(e){var r;return((r=e.account)==null?void 0:r.type)==="local"?[e.account.address]:(await e.request({method:"eth_accounts"},{dedupe:!0})).map(n=>Qi(n))}async function Nv(e,t={}){const{account:r=e.account,chainId:n}=t,i=r?ke(r):void 0,s=n?[i==null?void 0:i.address,[K(n)]]:[i==null?void 0:i.address],o=await e.request({method:"wallet_getCapabilities",params:s}),a={};for(const[c,f]of Object.entries(o)){a[Number(c)]={};for(let[u,d]of Object.entries(f))u==="addSubAccount"&&(u="unstable_addSubAccount"),a[Number(c)][u]=d}return typeof n=="number"?a[n]:a}async function Fv(e){return await e.request({method:"wallet_getPermissions"},{dedupe:!0})}async function O0(e,t){var c;const{account:r=e.account,chainId:n,nonce:i}=t;if(!r)throw new cn({docsPath:"/docs/eip7702/prepareAuthorization"});const s=ke(r),o=(()=>{if(t.executor)return t.executor==="self"?t.executor:ke(t.executor)})(),a={address:t.contractAddress??t.address,chainId:n,nonce:i};return typeof a.chainId>"u"&&(a.chainId=((c=e.chain)==null?void 0:c.id)??await ee(e,Zn,"getChainId")({})),typeof a.nonce>"u"&&(a.nonce=await ee(e,Tu,"getTransactionCount")({address:s.address,blockTag:"pending"}),(o==="self"||o!=null&&o.address&&ss(o.address,s.address))&&(a.nonce+=1)),a}async function $v(e){return(await e.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(r=>Tp(r))}async function Uv(e,t){return e.request({method:"wallet_requestPermissions",params:[t]},{retryCount:0})}async function Hv(e,t){const{id:r}=t;await e.request({method:"wallet_showCallsStatus",params:[r]})}async function Lv(e,t){const{account:r=e.account}=t;if(!r)throw new cn({docsPath:"/docs/eip7702/signAuthorization"});const n=ke(r);if(!n.signAuthorization)throw new $s({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});const i=await O0(e,t);return n.signAuthorization(i)}async function Mv(e,{account:t=e.account,message:r}){if(!t)throw new cn({docsPath:"/docs/actions/wallet/signMessage"});const n=ke(t);if(n.signMessage)return n.signMessage({message:r});const i=typeof r=="string"?Rn(r):r.raw instanceof Uint8Array?je(r.raw):r.raw;return e.request({method:"personal_sign",params:[i,n.address]},{retryCount:0})}async function Dv(e,t){var f,u,d,y;const{account:r=e.account,chain:n=e.chain,...i}=t;if(!r)throw new cn({docsPath:"/docs/actions/wallet/signTransaction"});const s=ke(r);on({account:s,...t});const o=await ee(e,Zn,"getChainId")({});n!==null&&Th({currentChainId:o,chain:n});const a=(n==null?void 0:n.formatters)||((f=e.chain)==null?void 0:f.formatters),c=((u=a==null?void 0:a.transactionRequest)==null?void 0:u.format)||Yn;return s.signTransaction?s.signTransaction({...i,chainId:o},{serializer:(y=(d=e.chain)==null?void 0:d.serializers)==null?void 0:y.transaction}):await e.request({method:"eth_signTransaction",params:[{...c(i),chainId:K(o),from:s.address}]},{retryCount:0})}async function jv(e,t){const{account:r=e.account,domain:n,message:i,primaryType:s}=t;if(!r)throw new cn({docsPath:"/docs/actions/wallet/signTypedData"});const o=ke(r),a={EIP712Domain:Jh({domain:n}),...t.types};if(Xh({domain:n,message:i,primaryType:s,types:a}),o.signTypedData)return o.signTypedData({domain:n,message:i,primaryType:s,types:a});const c=C1({domain:n,message:i,primaryType:s,types:a});return e.request({method:"eth_signTypedData_v4",params:[o.address,c]},{retryCount:0})}async function zv(e,{id:t}){await e.request({method:"wallet_switchEthereumChain",params:[{chainId:K(t)}]},{retryCount:0})}async function qv(e,t){return await e.request({method:"wallet_watchAsset",params:t},{retryCount:0})}function Gv(e){return{addChain:t=>Ov(e,t),deployContract:t=>Cv(e,t),getAddresses:()=>Rv(e),getCallsStatus:t=>Nh(e,t),getCapabilities:t=>Nv(e,t),getChainId:()=>Zn(e),getPermissions:()=>Fv(e),prepareAuthorization:t=>O0(e,t),prepareTransactionRequest:t=>lo(e,t),requestAddresses:()=>$v(e),requestPermissions:t=>Uv(e,t),sendCalls:t=>Lw(e,t),sendRawTransaction:t=>qu(e,t),sendTransaction:t=>wo(e,t),showCallsStatus:t=>Hv(e,t),signAuthorization:t=>Lv(e,t),signMessage:t=>Mv(e,t),signTransaction:t=>Dv(e,t),signTypedData:t=>jv(e,t),switchChain:t=>zv(e,t),waitForCallsStatus:t=>Mw(e,t),watchAsset:t=>qv(e,t),writeContract:t=>kh(e,t)}}function ra(e){const{key:t="wallet",name:r="Wallet Client",transport:n}=e;return $h({...e,key:t,name:r,transport:n,type:"walletClient"}).extend(Gv)}const Hs={mainnet:{orderbook:"https://api.garden.finance",auth:"https://api.garden.finance/auth",quote:"https://api.garden.finance/quote",info:"https://api.garden.finance/info",evmRelay:"https://api.garden.finance/relayer",solanaRelay:"https://solana-relayer.garden.finance/",starknetRelay:"https://api.garden.finance/starknet"},testnet:{orderbook:"https://testnet.api.garden.finance",auth:"https://testnet.api.garden.finance/auth",quote:"https://testnet.api.garden.finance/quote",info:"https://testnet.api.garden.finance/info",evmRelay:"https://testnet.api.garden.finance/relayer",solanaRelay:"https://solana-relay.garden.finance",starknetRelay:"https://testnet.api.garden.finance/starknet"},localnet:{orderbook:"",auth:"",quote:"",info:"",evmRelay:"",starknetRelay:"",solanaRelay:""}},Wi={[x.Network.MAINNET]:{chainId:"0x534e5f4d41494e",nodeUrl:"https://starknet-mainnet.public.blastapi.io/rpc/v0_8"},[x.Network.TESTNET]:{chainId:"0x534e5f5345504f4c4941",nodeUrl:"https://starknet-sepolia.public.blastapi.io/rpc/v0_8"},[x.Network.LOCALNET]:{chainId:"",nodeUrl:""}},Xc={[x.Network.MAINNET]:"9cBuPNiHXiMNg3Fin8xLCGJQBTXjYQTFtyaFQv2uiM1H",[x.Network.TESTNET]:"ANUVKxeqaec3bf4DVPqLTnG1PT3Fng56wPcE7LXAb46Q",[x.Network.LOCALNET]:"AKnL4NNf3DGWZJS6cPknBuEGnVsV4A4m5tgebLHaRSZ9"},C0={mainnet:"2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",staging:"6eksgdCnSjUaGQWZ6iYvauv1qzvYPF33RTGTM1ZuyENx"},gd={chain:le.SupportedAssets.mainnet.base_cbBTC.chain,asset:le.SupportedAssets.mainnet.base_cbBTC.atomicSwapAddress};var In=(e=>(e.SLOW="SLOW",e.MEDIUM="MEDIUM",e.FAST="FAST",e))(In||{}),at=(e=>(e.Mainnet="Mainnet",e.Testnet="Testnet",e.Regtest="Regtest",e))(at||{}),Ls=(e=>(e.ALL="ALL",e.IN="IN",e.OUT="OUT",e))(Ls||{});const Vv={SLOW:"economyFee",MEDIUM:"hourFee",FAST:"fastestFee"};function Jc(e){const t=typeof e=="string"?e:e.environment,r=t===x.Environment.MAINNET?Hs.mainnet:x.Environment.TESTNET?Hs.testnet:Hs.localnet;return{api:typeof e=="string"?r:{...r,...e},environment:t}}function Qc(e){return typeof e=="string"&&(e=Buffer.from(e,"hex")),e.length===32?e:e.subarray(1,33)}function yn(e,t){if(!e)throw new Error(t)}function Wv(e){return Buffer.concat([Uint8Array.from([192]),Kv(e)])}function Kv(e){const t=xf.encodingLength(e.length),r=Buffer.allocUnsafe(t);return xf.encode(e.length,r),Buffer.concat([r,e])}function Yv(e,t){if(e.compare(t)>0){const r=e;e=t,t=r}return[e,t]}const Ar=e=>e.length===64?e:e.slice(2),Zv=e=>{if(!e)return!1;try{const t=Buffer.from(e,"hex");return bt.isPoint(t)}catch{return!1}},eu=(e,t,r,n)=>e+":"+t.toLowerCase()+"::"+r+":"+n.toLowerCase();function Xv(e,t){if(!e)return!1;const r=t===x.Environment.MAINNET?pe.networks.bitcoin:t===x.Environment.TESTNET?pe.networks.testnet:pe.networks.regtest;if(!r)return!1;pe.initEccLib(bt);try{return pe.address.toOutputScript(e,r),!0}catch{return!1}}const Jv=e=>{switch(e){case x.Environment.MAINNET:return at.Mainnet;case x.Environment.TESTNET:return at.Testnet;case x.Environment.LOCALNET:return at.Regtest;default:throw new Error(`Invalid bitcoin network ${e}`)}},Qv=e=>{const t=e.toLowerCase().replace("0x","");return/^[0-9a-f]+$/.test(t)},eE=e=>{if(typeof e=="object"&&"r"in e&&"s"in e)return x.Ok([e.r.toString(),e.s.toString()]);if(Array.isArray(e)){const t=e.map(r=>typeof r=="string"&&r.startsWith("0x")&&Qv(r)?BigInt(r).toString():r);return x.Ok(t)}return x.Err("Invalid signature format")};function tu(e){return Buffer.from(e,"hex").reverse()}function ru(e){return typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"}const bd=async(e,t)=>{const r=Date.now(),n=3e4,i=2e3;for(;Date.now()-r<n;){const s=await e.getLatestBlockhash(),o=await e.confirmTransaction({signature:t,blockhash:s.blockhash,lastValidBlockHeight:s.lastValidBlockHeight},"confirmed");if(o.value&&o.value.err==null)return console.log("Tx Confirmed ✅"),!0;console.log("Tx not confirmed yet. Retrying in 2 seconds..."),await new Promise(a=>setTimeout(a,i))}return!1};var fe=(e=>(e.Created="Created",e.Matched="Matched",e.InitiateDetected="InitiateDetected",e.Initiated="Initiated",e.CounterPartyInitiateDetected="CounterPartyInitiateDetected",e.CounterPartyInitiated="CounterPartyInitiated",e.RedeemDetected="RedeemDetected",e.Redeemed="Redeemed",e.CounterPartyRedeemDetected="CounterPartyRedeemDetected",e.CounterPartyRedeemed="CounterPartyRedeemed",e.Completed="Completed",e.CounterPartySwapExpired="CounterPartySwapExpired",e.Expired="Expired",e.RefundDetected="RefundDetected",e.Refunded="Refunded",e.CounterPartyRefundDetected="CounterPartyRefundDetected",e.CounterPartyRefunded="CounterPartyRefunded",e.Cancelled="Cancelled",e.DeadLineExceeded="DeadLineExceeded",e))(fe||{}),Ee=(e=>(e.Idle="Idle",e.InitiateDetected="InitiateDetected",e.Initiated="Initiated",e.RedeemDetected="RedeemDetected",e.Redeemed="Redeemed",e.RefundDetected="RefundDetected",e.Refunded="Refunded",e.Expired="Expired",e))(Ee||{});const Qu=(e,t,r)=>{const n=nu(e.source_swap,t),i=nu(e.destination_swap,r);if(i===Ee.RedeemDetected)return fe.RedeemDetected;if(i===Ee.Redeemed)return fe.Redeemed;if(n===Ee.Refunded)return fe.Refunded;if(n===Ee.RefundDetected)return fe.RefundDetected;if(i===Ee.Expired)return fe.CounterPartySwapExpired;if(n===Ee.Expired)return fe.Expired;if(i===Ee.Refunded)return fe.CounterPartyRefunded;if(i===Ee.RefundDetected)return fe.CounterPartyRefundDetected;const s=Number(e.create_order.additional_data.deadline);return i===Ee.Initiated?fe.CounterPartyInitiated:i===Ee.InitiateDetected?fe.CounterPartyInitiateDetected:Ki(s,12)?fe.DeadLineExceeded:n===Ee.Initiated?fe.Initiated:Ki(s,1)?fe.DeadLineExceeded:n===Ee.InitiateDetected?fe.InitiateDetected:n===Ee.Redeemed?fe.CounterPartyRedeemed:n===Ee.RedeemDetected?fe.CounterPartyRedeemDetected:fe.Matched},nu=(e,t)=>{if(e.redeem_tx_hash)return Number(e.redeem_block_number)?Ee.Redeemed:Ee.RedeemDetected;if(e.refund_tx_hash)return Number(e.refund_block_number)?Ee.Refunded:Ee.RefundDetected;if(Number(e.initiate_block_number)){const r=Number(e.initiate_block_number)+e.timelock;if(t>r)return Ee.Expired}return e.initiate_tx_hash?Number(e.initiate_block_number)?Ee.Initiated:Ee.InitiateDetected:Ee.Idle},tE=(e,t,r)=>{const n=Qu(e,t,r);return ef(n)},ef=e=>{switch(e){case fe.Matched:return ve.Initiate;case fe.CounterPartyInitiated:case fe.CounterPartyInitiateDetected:case fe.RedeemDetected:return ve.Redeem;case fe.Expired:return ve.Refund;default:return ve.Idle}},Ki=(e,t=0)=>{const r=Date.now(),n=e*1e3+t*36e5;return r>=n},rE=e=>e.filter(t=>!R0(t)),R0=e=>{const{source_swap:t,create_order:r}=e,{initiate_tx_hash:n,initiate_block_number:i}=t,{deadline:s}=r.additional_data;return n&&Number(i)?!1:n&&!Number(i)?Ki(Number(s),12):n?!1:Ki(Number(s),1)},nE=Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),iE=Buffer.from("483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8","hex"),sE=Buffer.concat([nE,iE]),oE=Buffer.from("0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0","hex"),wd={failedToCreateInternalPubkey:"failed to create internal pubkey"};function aE(){const e=oe.crypto.sha256(Buffer.from("GardenHTLC","utf-8")),t=bt.pointMultiply(Buffer.concat([Buffer.from("04","hex"),sE]),e);if(!t)throw new Error(wd.failedToCreateInternalPubkey);const r=bt.pointAdd(oE,t);if(!r)throw new Error(wd.failedToCreateInternalPubkey);return Qc(Buffer.from(r))}var Kt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function N0(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var r=function n(){return this instanceof n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}),r}var _e={},qe={},un={},So={};So.byteLength=fE;So.toByteArray=lE;So.fromByteArray=yE;var qt=[],mt=[],cE=typeof Uint8Array<"u"?Uint8Array:Array,na="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var mn=0,uE=na.length;mn<uE;++mn)qt[mn]=na[mn],mt[na.charCodeAt(mn)]=mn;mt[45]=62;mt[95]=63;function F0(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var n=r===t?0:4-r%4;return[r,n]}function fE(e){var t=F0(e),r=t[0],n=t[1];return(r+n)*3/4-n}function dE(e,t,r){return(t+r)*3/4-r}function lE(e){var t,r=F0(e),n=r[0],i=r[1],s=new cE(dE(e,n,i)),o=0,a=i>0?n-4:n,c;for(c=0;c<a;c+=4)t=mt[e.charCodeAt(c)]<<18|mt[e.charCodeAt(c+1)]<<12|mt[e.charCodeAt(c+2)]<<6|mt[e.charCodeAt(c+3)],s[o++]=t>>16&255,s[o++]=t>>8&255,s[o++]=t&255;return i===2&&(t=mt[e.charCodeAt(c)]<<2|mt[e.charCodeAt(c+1)]>>4,s[o++]=t&255),i===1&&(t=mt[e.charCodeAt(c)]<<10|mt[e.charCodeAt(c+1)]<<4|mt[e.charCodeAt(c+2)]>>2,s[o++]=t>>8&255,s[o++]=t&255),s}function pE(e){return qt[e>>18&63]+qt[e>>12&63]+qt[e>>6&63]+qt[e&63]}function hE(e,t,r){for(var n,i=[],s=t;s<r;s+=3)n=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(e[s+2]&255),i.push(pE(n));return i.join("")}function yE(e){for(var t,r=e.length,n=r%3,i=[],s=16383,o=0,a=r-n;o<a;o+=s)i.push(hE(e,o,o+s>a?a:o+s));return n===1?(t=e[r-1],i.push(qt[t>>2]+qt[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],i.push(qt[t>>10]+qt[t>>4&63]+qt[t<<2&63]+"=")),i.join("")}var tf={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */tf.read=function(e,t,r,n,i){var s,o,a=i*8-n-1,c=(1<<a)-1,f=c>>1,u=-7,d=r?i-1:0,y=r?-1:1,p=e[t+d];for(d+=y,s=p&(1<<-u)-1,p>>=-u,u+=a;u>0;s=s*256+e[t+d],d+=y,u-=8);for(o=s&(1<<-u)-1,s>>=-u,u+=n;u>0;o=o*256+e[t+d],d+=y,u-=8);if(s===0)s=1-f;else{if(s===c)return o?NaN:(p?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-f}return(p?-1:1)*o*Math.pow(2,s-n)};tf.write=function(e,t,r,n,i,s){var o,a,c,f=s*8-i-1,u=(1<<f)-1,d=u>>1,y=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:s-1,g=n?1:-1,b=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+d>=1?t+=y/c:t+=y*Math.pow(2,1-d),t*c>=2&&(o++,c/=2),o+d>=u?(a=0,o=u):o+d>=1?(a=(t*c-1)*Math.pow(2,i),o=o+d):(a=t*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;e[r+p]=a&255,p+=g,a/=256,i-=8);for(o=o<<i|a,f+=i;f>0;e[r+p]=o&255,p+=g,o/=256,f-=8);e[r+p-g]|=b*128};/*!
39
+ `),{cause:t,name:"TipAboveFeeCapError"})}}Object.defineProperty(Vi,"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 is extends D{constructor({cause:t}){super(`An error occurred while executing: ${t==null?void 0:t.shortMessage}`,{cause:t,name:"UnknownNodeError"})}}function ao(e,t){const r=(e.details||"").toLowerCase(),n=e instanceof D?e.walk(i=>(i==null?void 0:i.code)===An.code):e;return n instanceof D?new An({cause:e,message:n.details}):An.nodeMessage.test(r)?new An({cause:e,message:e.details}):Qr.nodeMessage.test(r)?new Qr({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas}):Pc.nodeMessage.test(r)?new Pc({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas}):Tc.nodeMessage.test(r)?new Tc({cause:e,nonce:t==null?void 0:t.nonce}):Ic.nodeMessage.test(r)?new Ic({cause:e,nonce:t==null?void 0:t.nonce}):kc.nodeMessage.test(r)?new kc({cause:e,nonce:t==null?void 0:t.nonce}):Bc.nodeMessage.test(r)?new Bc({cause:e}):Oc.nodeMessage.test(r)?new Oc({cause:e,gas:t==null?void 0:t.gas}):Cc.nodeMessage.test(r)?new Cc({cause:e,gas:t==null?void 0:t.gas}):Rc.nodeMessage.test(r)?new Rc({cause:e}):Vi.nodeMessage.test(r)?new Vi({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas,maxPriorityFeePerGas:t==null?void 0:t.maxPriorityFeePerGas}):new is({cause:e})}function Eb(e,{docsPath:t,...r}){const n=(()=>{const i=ao(e,r);return i instanceof is?e:i})();return new vb(n,{docsPath:t,...r})}function co(e,{format:t}){if(!t)return{};const r={};function n(s){const o=Object.keys(s);for(const a of o)a in e&&(r[a]=e[a]),s[a]&&typeof s[a]=="object"&&!Array.isArray(s[a])&&n(s[a])}const i=t(e||{});return n(i),r}function xu(e,t){return({exclude:r,format:n})=>({exclude:r,format:i=>{const s=t(i);if(r)for(const o of r)delete s[o];return{...s,...n(i)}},type:e})}const xb={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function Yn(e){const t={};return typeof e.authorizationList<"u"&&(t.authorizationList=Ab(e.authorizationList)),typeof e.accessList<"u"&&(t.accessList=e.accessList),typeof e.blobVersionedHashes<"u"&&(t.blobVersionedHashes=e.blobVersionedHashes),typeof e.blobs<"u"&&(typeof e.blobs[0]!="string"?t.blobs=e.blobs.map(r=>Ce(r)):t.blobs=e.blobs),typeof e.data<"u"&&(t.data=e.data),typeof e.from<"u"&&(t.from=e.from),typeof e.gas<"u"&&(t.gas=K(e.gas)),typeof e.gasPrice<"u"&&(t.gasPrice=K(e.gasPrice)),typeof e.maxFeePerBlobGas<"u"&&(t.maxFeePerBlobGas=K(e.maxFeePerBlobGas)),typeof e.maxFeePerGas<"u"&&(t.maxFeePerGas=K(e.maxFeePerGas)),typeof e.maxPriorityFeePerGas<"u"&&(t.maxPriorityFeePerGas=K(e.maxPriorityFeePerGas)),typeof e.nonce<"u"&&(t.nonce=K(e.nonce)),typeof e.to<"u"&&(t.to=e.to),typeof e.type<"u"&&(t.type=xb[e.type]),typeof e.value<"u"&&(t.value=K(e.value)),t}function Ab(e){return e.map(t=>({address:t.address,r:t.r?K(BigInt(t.r)):t.r,s:t.s?K(BigInt(t.s)):t.s,chainId:K(t.chainId),nonce:K(t.nonce),...typeof t.yParity<"u"?{yParity:K(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:K(t.v)}:{}}))}function zf(e){if(!(!e||e.length===0))return e.reduce((t,{slot:r,value:n})=>{if(r.length!==66)throw new If({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new If({size:n.length,targetSize:66,type:"hex"});return t[r]=n,t},{})}function _b(e){const{balance:t,nonce:r,state:n,stateDiff:i,code:s}=e,o={};if(s!==void 0&&(o.code=s),t!==void 0&&(o.balance=K(t)),r!==void 0&&(o.nonce=K(r)),n!==void 0&&(o.state=zf(n)),i!==void 0){if(o.state)throw new eb;o.stateDiff=zf(i)}return o}function Au(e){if(!e)return;const t={};for(const{address:r,...n}of e){if(!Fe(r,{strict:!1}))throw new tt({address:r});if(t[r])throw new Qg({address:r});t[r]=_b(n)}return t}const uo=2n**256n-1n;function on(e){const{account:t,gasPrice:r,maxFeePerGas:n,maxPriorityFeePerGas:i,to:s}=e,o=t?ke(t):void 0;if(o&&!Fe(o.address))throw new tt({address:o.address});if(s&&!Fe(s))throw new tt({address:s});if(typeof r<"u"&&(typeof n<"u"||typeof i<"u"))throw new rb;if(n&&n>uo)throw new Qr({maxFeePerGas:n});if(i&&n&&i>n)throw new Vi({maxFeePerGas:n,maxPriorityFeePerGas:i})}class Sb extends D{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class _u extends D{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class Pb extends D{constructor({maxPriorityFeePerGas:t}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${it(t)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class Vp extends D{constructor({blockHash:t,blockNumber:r}){let n="Block";t&&(n=`Block at hash "${t}"`),r&&(n=`Block at number "${r}"`),super(`${n} could not be found.`,{name:"BlockNotFoundError"})}}const Wp={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function fo(e){const t={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,chainId:e.chainId?Et(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?Et(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?Wp[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};return e.authorizationList&&(t.authorizationList=Ib(e.authorizationList)),t.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof t.v=="bigint"){if(t.v===0n||t.v===27n)return 0;if(t.v===1n||t.v===28n)return 1;if(t.v>=35n)return t.v%2n===0n?1:0}})(),t.type==="legacy"&&(delete t.accessList,delete t.maxFeePerBlobGas,delete t.maxFeePerGas,delete t.maxPriorityFeePerGas,delete t.yParity),t.type==="eip2930"&&(delete t.maxFeePerBlobGas,delete t.maxFeePerGas,delete t.maxPriorityFeePerGas),t.type==="eip1559"&&delete t.maxFeePerBlobGas,t}const Tb=xu("transaction",fo);function Ib(e){return e.map(t=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}function Su(e){const t=(e.transactions??[]).map(r=>typeof r=="string"?r:fo(r));return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:t,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}const kb=xu("block",Su);async function Gt(e,{blockHash:t,blockNumber:r,blockTag:n,includeTransactions:i}={}){var u,d,y;const s=n??"latest",o=i??!1,a=r!==void 0?K(r):void 0;let c=null;if(t?c=await e.request({method:"eth_getBlockByHash",params:[t,o]},{dedupe:!0}):c=await e.request({method:"eth_getBlockByNumber",params:[a||s,o]},{dedupe:!!a}),!c)throw new Vp({blockHash:t,blockNumber:r});return(((y=(d=(u=e.chain)==null?void 0:u.formatters)==null?void 0:d.block)==null?void 0:y.format)||Su)(c)}async function Pu(e){const t=await e.request({method:"eth_gasPrice"});return BigInt(t)}async function Bb(e,t){return Kp(e,t)}async function Kp(e,t){var s,o;const{block:r,chain:n=e.chain,request:i}=t||{};try{const a=((s=n==null?void 0:n.fees)==null?void 0:s.maxPriorityFeePerGas)??((o=n==null?void 0:n.fees)==null?void 0:o.defaultPriorityFee);if(typeof a=="function"){const f=r||await ee(e,Gt,"getBlock")({}),u=await a({block:f,client:e,request:i});if(u===null)throw new Error;return u}if(typeof a<"u")return a;const c=await e.request({method:"eth_maxPriorityFeePerGas"});return Ue(c)}catch{const[a,c]=await Promise.all([r?Promise.resolve(r):ee(e,Gt,"getBlock")({}),ee(e,Pu,"getGasPrice")({})]);if(typeof a.baseFeePerGas!="bigint")throw new _u;const f=c-a.baseFeePerGas;return f<0n?0n:f}}async function Ob(e,t){return Nc(e,t)}async function Nc(e,t){var y,p;const{block:r,chain:n=e.chain,request:i,type:s="eip1559"}=t||{},o=await(async()=>{var g,b;return typeof((g=n==null?void 0:n.fees)==null?void 0:g.baseFeeMultiplier)=="function"?n.fees.baseFeeMultiplier({block:r,client:e,request:i}):((b=n==null?void 0:n.fees)==null?void 0:b.baseFeeMultiplier)??1.2})();if(o<1)throw new Sb;const c=10**(((y=o.toString().split(".")[1])==null?void 0:y.length)??0),f=g=>g*BigInt(Math.ceil(o*c))/BigInt(c),u=r||await ee(e,Gt,"getBlock")({});if(typeof((p=n==null?void 0:n.fees)==null?void 0:p.estimateFeesPerGas)=="function"){const g=await n.fees.estimateFeesPerGas({block:r,client:e,multiply:f,request:i,type:s});if(g!==null)return g}if(s==="eip1559"){if(typeof u.baseFeePerGas!="bigint")throw new _u;const g=typeof(i==null?void 0:i.maxPriorityFeePerGas)=="bigint"?i.maxPriorityFeePerGas:await Kp(e,{block:u,chain:n,request:i}),b=f(u.baseFeePerGas);return{maxFeePerGas:(i==null?void 0:i.maxFeePerGas)??b+g,maxPriorityFeePerGas:g}}return{gasPrice:(i==null?void 0:i.gasPrice)??f(await ee(e,Pu,"getGasPrice")({}))}}async function Tu(e,{address:t,blockTag:r="latest",blockNumber:n}){const i=await e.request({method:"eth_getTransactionCount",params:[t,typeof n=="bigint"?K(n):r]},{dedupe:!!n});return Et(i)}function Iu(e){const{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(s=>kt(s)):e.blobs,i=[];for(const s of n)i.push(Uint8Array.from(t.blobToKzgCommitment(s)));return r==="bytes"?i:i.map(s=>Ce(s))}function ku(e){const{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(o=>kt(o)):e.blobs,i=typeof e.commitments[0]=="string"?e.commitments.map(o=>kt(o)):e.commitments,s=[];for(let o=0;o<n.length;o++){const a=n[o],c=i[o];s.push(Uint8Array.from(t.computeBlobKzgProof(a,c)))}return r==="bytes"?s:s.map(o=>Ce(o))}function Cb(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),c=n?4:0,f=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+f,a,n)}function Rb(e,t,r){return e&t^~e&r}function Nb(e,t,r){return e&t^e&r^t&r}let Yp=class extends pu{constructor(t,r,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(t),this.view=Lo(this.buffer)}update(t){Nn(this),t=eo(t),Bt(t);const{view:r,buffer:n,blockLen:i}=this,s=t.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=Lo(t);for(;i<=s-o;o+=i)this.process(c,o);continue}n.set(t.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Nn(this),wp(t,this),this.finished=!0;const{buffer:r,view:n,blockLen:i,isLE:s}=this;let{pos:o}=this;r[o++]=128,Or(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(n,0),o=0);for(let d=o;d<i;d++)r[d]=0;Cb(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=Lo(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const f=c/4,u=this.get();if(f>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<f;d++)a.setUint32(4*d,u[d],s)}digest(){const{buffer:t,outputLen:r}=this;this.digestInto(t);const n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:r,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return t.destroyed=o,t.finished=s,t.length=i,t.pos=a,i%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}};const mr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),gr=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]),Fb=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]),br=new Uint32Array(64);let Bu=class extends Yp{constructor(t=32){super(64,t,8,!1),this.A=mr[0]|0,this.B=mr[1]|0,this.C=mr[2]|0,this.D=mr[3]|0,this.E=mr[4]|0,this.F=mr[5]|0,this.G=mr[6]|0,this.H=mr[7]|0}get(){const{A:t,B:r,C:n,D:i,E:s,F:o,G:a,H:c}=this;return[t,r,n,i,s,o,a,c]}set(t,r,n,i,s,o,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(t,r){for(let d=0;d<16;d++,r+=4)br[d]=t.getUint32(r,!1);for(let d=16;d<64;d++){const y=br[d-15],p=br[d-2],g=Ft(y,7)^Ft(y,18)^y>>>3,b=Ft(p,17)^Ft(p,19)^p>>>10;br[d]=b+br[d-7]+g+br[d-16]|0}let{A:n,B:i,C:s,D:o,E:a,F:c,G:f,H:u}=this;for(let d=0;d<64;d++){const y=Ft(a,6)^Ft(a,11)^Ft(a,25),p=u+y+Rb(a,c,f)+Fb[d]+br[d]|0,b=(Ft(n,2)^Ft(n,13)^Ft(n,22))+Nb(n,i,s)|0;u=f,f=c,c=a,a=o+p|0,o=s,s=i,i=n,n=p+b|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,u=u+this.H|0,this.set(n,i,s,o,a,c,f,u)}roundClean(){Or(br)}destroy(){this.set(0,0,0,0,0,0,0,0),Or(this.buffer)}},Zp=class extends Bu{constructor(){super(28),this.A=gr[0]|0,this.B=gr[1]|0,this.C=gr[2]|0,this.D=gr[3]|0,this.E=gr[4]|0,this.F=gr[5]|0,this.G=gr[6]|0,this.H=gr[7]|0}};const Xp=to(()=>new Bu),$b=to(()=>new Zp),Ub=Bu,Jp=Xp,Hb=Zp,Lb=$b,Mb=Object.freeze(Object.defineProperty({__proto__:null,SHA224:Hb,SHA256:Ub,sha224:Lb,sha256:Jp},Symbol.toStringTag,{value:"Module"}));function di(e,t){const r=t||"hex",n=Jp(It(e,{strict:!1})?Kn(e):e);return r==="bytes"?n:je(n)}function Db(e){const{commitment:t,version:r=1}=e,n=e.to??(typeof t=="string"?"hex":"bytes"),i=di(t,"bytes");return i.set([r],0),n==="bytes"?i:Ce(i)}function Qp(e){const{commitments:t,version:r}=e,n=e.to??(typeof t[0]=="string"?"hex":"bytes"),i=[];for(const s of t)i.push(Db({commitment:s,to:n,version:r}));return i}const qf=6,eh=32,Ou=4096,th=eh*Ou,Gf=th*qf-1-1*Ou*qf,rh=1;class jb extends D{constructor({maxSize:t,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${t} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}}class nh extends D{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class zb extends D{constructor({hash:t,size:r}){super(`Versioned hash "${t}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}}class qb extends D{constructor({hash:t,version:r}){super(`Versioned hash "${t}" version is invalid.`,{metaMessages:[`Expected: ${rh}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}}function Gb(e){const t=e.to??(typeof e.data=="string"?"hex":"bytes"),r=typeof e.data=="string"?kt(e.data):e.data,n=Se(r);if(!n)throw new nh;if(n>Gf)throw new jb({maxSize:Gf,size:n});const i=[];let s=!0,o=0;for(;s;){const a=wu(new Uint8Array(th));let c=0;for(;c<Ou;){const f=r.slice(o,o+(eh-1));if(a.pushByte(0),a.pushBytes(f),f.length<31){a.pushByte(128),s=!1;break}c++,o+=31}i.push(a)}return t==="bytes"?i.map(a=>a.bytes):i.map(a=>Ce(a.bytes))}function ih(e){const{data:t,kzg:r,to:n}=e,i=e.blobs??Gb({data:t,to:n}),s=e.commitments??Iu({blobs:i,kzg:r,to:n}),o=e.proofs??ku({blobs:i,commitments:s,kzg:r,to:n}),a=[];for(let c=0;c<i.length;c++)a.push({blob:i[c],commitment:s[c],proof:o[c]});return a}function sh(e){if(e.type)return e.type;if(typeof e.authorizationList<"u")return"eip7702";if(typeof e.blobs<"u"||typeof e.blobVersionedHashes<"u"||typeof e.maxFeePerBlobGas<"u"||typeof e.sidecars<"u")return"eip4844";if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")return"eip1559";if(typeof e.gasPrice<"u")return typeof e.accessList<"u"?"eip2930":"legacy";throw new ib({transaction:e})}async function Zn(e){const t=await e.request({method:"eth_chainId"},{dedupe:!0});return Et(t)}const oh=["blobVersionedHashes","chainId","fees","gas","nonce","type"],Vf=new Map;async function lo(e,t){const{account:r=e.account,blobs:n,chain:i,gas:s,kzg:o,nonce:a,nonceManager:c,parameters:f=oh,type:u}=t,d=r&&ke(r),y={...t,...d?{from:d==null?void 0:d.address}:{}};let p;async function g(){return p||(p=await ee(e,Gt,"getBlock")({blockTag:"latest"}),p)}let b;async function E(){return b||(i?i.id:typeof t.chainId<"u"?t.chainId:(b=await ee(e,Zn,"getChainId")({}),b))}if(f.includes("nonce")&&typeof a>"u"&&d)if(c){const A=await E();y.nonce=await c.consume({address:d.address,chainId:A,client:e})}else y.nonce=await ee(e,Tu,"getTransactionCount")({address:d.address,blockTag:"pending"});if((f.includes("blobVersionedHashes")||f.includes("sidecars"))&&n&&o){const A=Iu({blobs:n,kzg:o});if(f.includes("blobVersionedHashes")){const P=Qp({commitments:A,to:"hex"});y.blobVersionedHashes=P}if(f.includes("sidecars")){const P=ku({blobs:n,commitments:A,kzg:o}),w=ih({blobs:n,commitments:A,proofs:P,to:"hex"});y.sidecars=w}}if(f.includes("chainId")&&(y.chainId=await E()),(f.includes("fees")||f.includes("type"))&&typeof u>"u")try{y.type=sh(y)}catch{let A=Vf.get(e.uid);if(typeof A>"u"){const P=await g();A=typeof(P==null?void 0:P.baseFeePerGas)=="bigint",Vf.set(e.uid,A)}y.type=A?"eip1559":"legacy"}if(f.includes("fees"))if(y.type!=="legacy"&&y.type!=="eip2930"){if(typeof y.maxFeePerGas>"u"||typeof y.maxPriorityFeePerGas>"u"){const A=await g(),{maxFeePerGas:P,maxPriorityFeePerGas:w}=await Nc(e,{block:A,chain:i,request:y});if(typeof t.maxPriorityFeePerGas>"u"&&t.maxFeePerGas&&t.maxFeePerGas<w)throw new Pb({maxPriorityFeePerGas:w});y.maxPriorityFeePerGas=w,y.maxFeePerGas=P}}else{if(typeof t.maxFeePerGas<"u"||typeof t.maxPriorityFeePerGas<"u")throw new _u;if(typeof t.gasPrice>"u"){const A=await g(),{gasPrice:P}=await Nc(e,{block:A,chain:i,request:y,type:"legacy"});y.gasPrice=P}}return f.includes("gas")&&typeof s>"u"&&(y.gas=await ee(e,Cu,"estimateGas")({...y,account:d&&{address:d.address,type:"json-rpc"}})),on(y),delete y.parameters,y}async function ah(e,{address:t,blockNumber:r,blockTag:n="latest"}){const i=typeof r=="bigint"?K(r):void 0,s=await e.request({method:"eth_getBalance",params:[t,i||n]});return BigInt(s)}async function Cu(e,t){var i,s,o;const{account:r=e.account}=t,n=r?ke(r):void 0;try{let V=function(X){const{block:J,request:M,rpcStateOverride:B}=X;return e.request({method:"eth_estimateGas",params:B?[M,J??"latest",B]:J?[M,J]:[M]})};const{accessList:a,authorizationList:c,blobs:f,blobVersionedHashes:u,blockNumber:d,blockTag:y,data:p,gas:g,gasPrice:b,maxFeePerBlobGas:E,maxFeePerGas:A,maxPriorityFeePerGas:P,nonce:w,value:_,stateOverride:T,...I}=await lo(e,{...t,parameters:(n==null?void 0:n.type)==="local"?void 0:["blobVersionedHashes"]}),L=(typeof d=="bigint"?K(d):void 0)||y,S=Au(T),$=await(async()=>{if(I.to)return I.to;if(c&&c.length>0)return await Gp({authorization:c[0]}).catch(()=>{throw new D("`to` is required. Could not infer from `authorizationList`")})})();on(t);const C=(o=(s=(i=e.chain)==null?void 0:i.formatters)==null?void 0:s.transactionRequest)==null?void 0:o.format,j=(C||Yn)({...co(I,{format:C}),from:n==null?void 0:n.address,accessList:a,authorizationList:c,blobs:f,blobVersionedHashes:u,data:p,gas:g,gasPrice:b,maxFeePerBlobGas:E,maxFeePerGas:A,maxPriorityFeePerGas:P,nonce:w,to:$,value:_});let Y=BigInt(await V({block:L,request:j,rpcStateOverride:S}));if(c){const X=await ah(e,{address:j.from}),J=await Promise.all(c.map(async M=>{const{address:B}=M,q=await V({block:L,request:{authorizationList:void 0,data:p,from:n==null?void 0:n.address,to:B,value:K(X)},rpcStateOverride:S}).catch(()=>100000n);return 2n*BigInt(q)}));Y+=J.reduce((M,B)=>M+B,0n)}return Y}catch(a){throw Eb(a,{...t,account:n,chain:e.chain})}}async function ch(e,t){const{abi:r,address:n,args:i,functionName:s,dataSuffix:o,...a}=t,c=At({abi:r,args:i,functionName:s});try{return await ee(e,Cu,"estimateGas")({data:`${c}${o?o.replace("0x",""):""}`,to:n,...a})}catch(f){const u=a.account?ke(a.account):void 0;throw Jr(f,{abi:r,address:n,args:i,docsPath:"/docs/contract/estimateContractGas",functionName:s,sender:u==null?void 0:u.address})}}function ss(e,t){if(!Fe(e,{strict:!1}))throw new tt({address:e});if(!Fe(t,{strict:!1}))throw new tt({address:t});return e.toLowerCase()===t.toLowerCase()}const Wf="/docs/contract/decodeEventLog";function Ru(e){const{abi:t,data:r,strict:n,topics:i}=e,s=n??!0,[o,...a]=i;if(!o)throw new Fm({docsPath:Wf});const c=t.find(b=>b.type==="event"&&o===ro(Tt(b)));if(!(c&&"name"in c)||c.type!=="event")throw new lp(o,{docsPath:Wf});const{name:f,inputs:u}=c,d=u==null?void 0:u.some(b=>!("name"in b&&b.name)),y=d?[]:{},p=u.map((b,E)=>[b,E]).filter(([b])=>"indexed"in b&&b.indexed);for(let b=0;b<p.length;b++){const[E,A]=p[b],P=a[b];if(!P)throw new Qs({abiItem:c,param:E});y[d?A:E.name||A]=Vb({param:E,value:P})}const g=u.filter(b=>!("indexed"in b&&b.indexed));if(g.length>0){if(r&&r!=="0x")try{const b=rs(g,r);if(b)if(d)for(let E=0;E<u.length;E++)y[E]=y[E]??b.shift();else for(let E=0;E<g.length;E++)y[g[E].name]=b[E]}catch(b){if(s)throw b instanceof fp||b instanceof Fp?new _i({abiItem:c,data:r,params:g,size:Se(r)}):b}else if(s)throw new _i({abiItem:c,data:"0x",params:g,size:0})}return{eventName:f,args:Object.values(y).length>0?y:void 0}}function Vb({param:e,value:t}){return e.type==="string"||e.type==="bytes"||e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/)?t:(rs([e],t)||[])[0]}function Nu(e){const{abi:t,args:r,logs:n,strict:i=!0}=e,s=(()=>{if(e.eventName)return Array.isArray(e.eventName)?e.eventName:[e.eventName]})();return n.map(o=>{var a;try{const c=t.find(u=>u.type==="event"&&o.topics[0]===ro(u));if(!c)return null;const f=Ru({...o,abi:[c],strict:i});return s&&!s.includes(f.eventName)||!Wb({args:f.args,inputs:c.inputs,matchArgs:r})?null:{...f,...o}}catch(c){let f,u;if(c instanceof lp)return null;if(c instanceof _i||c instanceof Qs){if(i)return null;f=c.abiItem.name,u=(a=c.abiItem.inputs)==null?void 0:a.some(d=>!("name"in d&&d.name))}return{...o,args:u?[]:{},eventName:f}}}).filter(Boolean)}function Wb(e){const{args:t,inputs:r,matchArgs:n}=e;if(!n)return!0;if(!t)return!1;function i(s,o,a){try{return s.type==="address"?ss(o,a):s.type==="string"||s.type==="bytes"?De(Kn(o))===a:o===a}catch{return!1}}return Array.isArray(t)&&Array.isArray(n)?n.every((s,o)=>{if(s==null)return!0;const a=r[o];return a?(Array.isArray(s)?s:[s]).some(f=>i(a,f,t[o])):!1}):typeof t=="object"&&!Array.isArray(t)&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).every(([s,o])=>{if(o==null)return!0;const a=r.find(f=>f.name===s);return a?(Array.isArray(o)?o:[o]).some(f=>i(a,f,t[s])):!1}):!1}function cr(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}async function Fu(e,{address:t,blockHash:r,fromBlock:n,toBlock:i,event:s,events:o,args:a,strict:c}={}){const f=c??!1,u=o??(s?[s]:void 0);let d=[];u&&(d=[u.flatMap(b=>ts({abi:[b],eventName:b.name,args:o?void 0:a}))],s&&(d=d[0]));let y;r?y=await e.request({method:"eth_getLogs",params:[{address:t,topics:d,blockHash:r}]}):y=await e.request({method:"eth_getLogs",params:[{address:t,topics:d,fromBlock:typeof n=="bigint"?K(n):n,toBlock:typeof i=="bigint"?K(i):i}]});const p=y.map(g=>cr(g));return u?Nu({abi:u,args:a,logs:p,strict:f}):p}async function $u(e,t){const{abi:r,address:n,args:i,blockHash:s,eventName:o,fromBlock:a,toBlock:c,strict:f}=t,u=o?sn({abi:r,name:o}):void 0,d=u?void 0:r.filter(y=>y.type==="event");return ee(e,Fu,"getLogs")({address:n,args:i,blockHash:s,event:u,events:d,fromBlock:a,toBlock:c,strict:f})}const jo="/docs/contract/decodeFunctionResult";function an(e){const{abi:t,args:r,functionName:n,data:i}=e;let s=t[0];if(n){const a=sn({abi:t,args:r,name:n});if(!a)throw new Cn(n,{docsPath:jo});s=a}if(s.type!=="function")throw new Cn(void 0,{docsPath:jo});if(!s.outputs)throw new pp(s.name,{docsPath:jo});const o=rs(s.outputs,i);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 Uu=BigInt(0),Fc=BigInt(1);function Ws(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function gs(e){const t=e.toString(16);return t.length&1?"0"+t:t}function uh(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?Uu:BigInt("0x"+e)}function po(e){return uh(Pi(e))}function fh(e){return Bt(e),uh(Pi(Uint8Array.from(e).reverse()))}function Hu(e,t){return lu(e.toString(16).padStart(t*2,"0"))}function dh(e,t){return Hu(e,t).reverse()}function mt(e,t,r){let n;if(typeof t=="string")try{n=lu(t)}catch(s){throw new Error(e+" must be hex string or Uint8Array, cause: "+s)}else if(du(t))n=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");const i=n.length;if(typeof r=="number"&&i!==r)throw new Error(e+" of length "+r+" expected, got "+i);return n}const zo=e=>typeof e=="bigint"&&Uu<=e;function Kb(e,t,r){return zo(e)&&zo(t)&&zo(r)&&t<=e&&e<r}function Yb(e,t,r,n){if(!Kb(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function Zb(e){let t;for(t=0;e>Uu;e>>=Fc,t+=1);return t}const ho=e=>(Fc<<BigInt(e))-Fc;function Xb(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");const n=p=>new Uint8Array(p),i=p=>Uint8Array.of(p);let s=n(e),o=n(e),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},f=(...p)=>r(o,s,...p),u=(p=n(0))=>{o=f(i(0),p),s=f(),p.length!==0&&(o=f(i(1),p),s=f())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let p=0;const g=[];for(;p<t;){s=f();const b=s.slice();g.push(b),p+=s.length}return Hr(...g)};return(p,g)=>{c(),u(p);let b;for(;!(b=g(d()));)u();return c(),b}}function Lu(e,t,r={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function n(i,s,o){const a=e[i];if(o&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${c}`)}Object.entries(t).forEach(([i,s])=>n(i,s,!1)),Object.entries(r).forEach(([i,s])=>n(i,s,!0))}function Kf(e){const t=new WeakMap;return(r,...n)=>{const i=t.get(r);if(i!==void 0)return i;const s=e(r,...n);return t.set(r,s),s}}const Jb="0.1.1";function Qb(){return Jb}class xe extends Error{constructor(t,r={}){const n=(()=>{var c;if(r.cause instanceof xe){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:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),i=r.cause instanceof xe&&r.cause.docsPath||r.docsPath,o=`https://oxlib.sh${i??""}`,a=[t||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||i?["",n?`Details: ${n}`:void 0,i?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
40
+ `);super(a,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,"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,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${Qb()}`}),this.cause=r.cause,this.details=n,this.docs=o,this.docsPath=i,this.shortMessage=t}walk(t){return lh(this,t)}}function lh(e,t){return t!=null&&t(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause?lh(e.cause,t):t?null:e}const ew="#__bigint";function tw(e,t,r){return JSON.stringify(e,(n,i)=>typeof i=="bigint"?i.toString()+ew:i,r)}function rw(e,t){if(Zf(e)>t)throw new lw({givenSize:Zf(e),maxSize:t})}const Xt={zero:48,nine:57,A:65,F:70,a:97,f:102};function Yf(e){if(e>=Xt.zero&&e<=Xt.nine)return e-Xt.zero;if(e>=Xt.A&&e<=Xt.F)return e-(Xt.A-10);if(e>=Xt.a&&e<=Xt.f)return e-(Xt.a-10)}function nw(e,t={}){const{dir:r,size:n=32}=t;if(n===0)return e;if(e.length>n)throw new pw({size:e.length,targetSize:n,type:"Bytes"});const i=new Uint8Array(n);for(let s=0;s<n;s++){const o=r==="right";i[o?s:n-s-1]=e[o?s:e.length-s-1]}return i}function Mu(e,t){if(xt(e)>t)throw new bw({givenSize:xt(e),maxSize:t})}function iw(e,t){if(typeof t=="number"&&t>0&&t>xt(e)-1)throw new gh({offset:t,position:"start",size:xt(e)})}function sw(e,t,r){if(typeof t=="number"&&typeof r=="number"&&xt(e)!==r-t)throw new gh({offset:r,position:"end",size:xt(e)})}function ph(e,t={}){const{dir:r,size:n=32}=t;if(n===0)return e;const i=e.replace("0x","");if(i.length>n*2)throw new ww({size:Math.ceil(i.length/2),targetSize:n,type:"Hex"});return`0x${i[r==="right"?"padEnd":"padStart"](n*2,"0")}`}const ow=new TextEncoder;function aw(e){return e instanceof Uint8Array?e:typeof e=="string"?uw(e):cw(e)}function cw(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function uw(e,t={}){const{size:r}=t;let n=e;r&&(Mu(e,r),n=tn(e,r));let i=n.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,o=new Uint8Array(s);for(let a=0,c=0;a<s;a++){const f=Yf(i.charCodeAt(c++)),u=Yf(i.charCodeAt(c++));if(f===void 0||u===void 0)throw new xe(`Invalid byte sequence ("${i[c-2]}${i[c-1]}" in "${i}").`);o[a]=f*16+u}return o}function fw(e,t={}){const{size:r}=t,n=ow.encode(e);return typeof r=="number"?(rw(n,r),dw(n,r)):n}function dw(e,t){return nw(e,{dir:"right",size:t})}function Zf(e){return e.length}let lw=class extends xe{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}},pw=class extends xe{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}};const hw=new TextEncoder,yw=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function mw(e,t={}){const{strict:r=!1}=t;if(!e)throw new Xf(e);if(typeof e!="string")throw new Xf(e);if(r&&!/^0x[0-9a-fA-F]*$/.test(e))throw new Jf(e);if(!e.startsWith("0x"))throw new Jf(e)}function Vt(...e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function hh(e,t={}){const r=`0x${Number(e)}`;return typeof t.size=="number"?(Mu(r,t.size),en(r,t.size)):r}function yh(e,t={}){let r="";for(let i=0;i<e.length;i++)r+=yw[e[i]];const n=`0x${r}`;return typeof t.size=="number"?(Mu(n,t.size),tn(n,t.size)):n}function Je(e,t={}){const{signed:r,size:n}=t,i=BigInt(e);let s;n?r?s=(1n<<BigInt(n)*8n-1n)-1n:s=2n**(BigInt(n)*8n)-1n:typeof e=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&r?-s-1n:0;if(s&&i>s||i<o){const f=typeof e=="bigint"?"n":"";throw new mh({max:s?`${s}${f}`:void 0,min:`${o}${f}`,signed:r,size:n,value:`${e}${f}`})}const c=`0x${(r&&i<0?(1n<<BigInt(n*8))+BigInt(i):i).toString(16)}`;return n?en(c,n):c}function Du(e,t={}){return yh(hw.encode(e),t)}function en(e,t){return ph(e,{dir:"left",size:t})}function tn(e,t){return ph(e,{dir:"right",size:t})}function ju(e,t,r,n={}){const{strict:i}=n;iw(e,t);const s=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;return i&&sw(s,t,r),s}function xt(e){return Math.ceil((e.length-2)/2)}function gw(e,t={}){const{strict:r=!1}=t;try{return mw(e,{strict:r}),!0}catch{return!1}}class mh extends xe{constructor({max:t,min:r,signed:n,size:i,value:s}){super(`Number \`${s}\` is not in safe${i?` ${i*8}-bit`:""}${n?" signed":" unsigned"} integer range ${t?`(\`${r}\` to \`${t}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class Xf extends xe{constructor(t){super(`Value \`${typeof t=="object"?tw(t):t}\` of type \`${typeof t}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class Jf extends xe{constructor(t){super(`Value \`${t}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}class bw extends xe{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}}class gh extends xe{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${t}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}class ww extends xe{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}function vw(e){return{address:e.address,amount:Je(e.amount),index:Je(e.index),validatorIndex:Je(e.validatorIndex)}}function bh(e){return{...typeof e.baseFeePerGas=="bigint"&&{baseFeePerGas:Je(e.baseFeePerGas)},...typeof e.blobBaseFee=="bigint"&&{blobBaseFee:Je(e.blobBaseFee)},...typeof e.feeRecipient=="string"&&{feeRecipient:e.feeRecipient},...typeof e.gasLimit=="bigint"&&{gasLimit:Je(e.gasLimit)},...typeof e.number=="bigint"&&{number:Je(e.number)},...typeof e.prevRandao=="bigint"&&{prevRandao:Je(e.prevRandao)},...typeof e.time=="bigint"&&{time:Je(e.time)},...e.withdrawals&&{withdrawals:e.withdrawals.map(vw)}}}const $c=[{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"}],Uc=[{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"}]}],wh=[{inputs:[],name:"ResolverNotFound",type:"error"},{inputs:[],name:"ResolverWildcardNotSupported",type:"error"},{inputs:[],name:"ResolverNotContract",type:"error"},{inputs:[{name:"returnData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{components:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"errors",type:"tuple[]"}],name:"HttpError",type:"error"}],vh=[...wh,{name:"resolve",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]},{name:"resolve",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"}]}],Ew=[...wh,{name:"reverse",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolvedAddress"},{type:"address",name:"reverseResolver"},{type:"address",name:"resolver"}]},{name:"reverse",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolvedAddress"},{type:"address",name:"reverseResolver"},{type:"address",name:"resolver"}]}],Qf=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],ed=[{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"}]}],td=[{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"}],xw="0x82ad56cb",Eh="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",Aw="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",_w="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572";class Hc extends D{constructor({blockNumber:t,chain:r,contract:n}){super(`Chain "${r.name}" does not support contract "${n.name}".`,{metaMessages:["This could be due to any of the following:",...t&&n.blockCreated&&n.blockCreated>t?[`- The contract "${n.name}" was not deployed until block ${n.blockCreated} (current block ${t}).`]:[`- The chain does not have the contract "${n.name}" configured.`]],name:"ChainDoesNotSupportContract"})}}class Sw extends D{constructor({chain:t,currentChainId:r}){super(`The current chain of the wallet (id: ${r}) does not match the target chain for the transaction (id: ${t.id} – ${t.name}).`,{metaMessages:[`Current Chain ID: ${r}`,`Expected Chain ID: ${t.id} – ${t.name}`],name:"ChainMismatchError"})}}class Pw extends D{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(`
41
+ `),{name:"ChainNotFoundError"})}}class xh extends D{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}class yo extends D{constructor({chainId:t}){super(typeof t=="number"?`Chain ID "${t}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}const qo="/docs/contract/encodeDeployData";function mo(e){const{abi:t,args:r,bytecode:n}=e;if(!r||r.length===0)return n;const i=t.find(o=>"type"in o&&o.type==="constructor");if(!i)throw new Bm({docsPath:qo});if(!("inputs"in i))throw new Sf({docsPath:qo});if(!i.inputs||i.inputs.length===0)throw new Sf({docsPath:qo});const s=pr(i.inputs,r);return Ct([n,s])}function Xn({blockNumber:e,chain:t,contract:r}){var i;const n=(i=t==null?void 0:t.contracts)==null?void 0:i[r];if(!n)throw new Hc({chain:t,contract:{name:r}});if(e&&n.blockCreated&&n.blockCreated>e)throw new Hc({blockNumber:e,chain:t,contract:{name:r,blockCreated:n.blockCreated}});return n.address}function Ah(e,{docsPath:t,...r}){const n=(()=>{const i=ao(e,r);return i instanceof is?e:i})();return new Dp(n,{docsPath:t,...r})}function zu(){let e=()=>{},t=()=>{};return{promise:new Promise((n,i)=>{e=n,t=i}),resolve:e,reject:t}}const Go=new Map;function _h({fn:e,id:t,shouldSplitBatch:r,wait:n=0,sort:i}){const s=async()=>{const u=c();o();const d=u.map(({args:y})=>y);d.length!==0&&e(d).then(y=>{i&&Array.isArray(y)&&y.sort(i);for(let p=0;p<u.length;p++){const{resolve:g}=u[p];g==null||g([y[p],y])}}).catch(y=>{for(let p=0;p<u.length;p++){const{reject:g}=u[p];g==null||g(y)}})},o=()=>Go.delete(t),a=()=>c().map(({args:u})=>u),c=()=>Go.get(t)||[],f=u=>Go.set(t,[...c(),u]);return{flush:o,async schedule(u){const{promise:d,resolve:y,reject:p}=zu();return(r==null?void 0:r([...a(),u]))&&s(),c().length>0?(f({args:u,resolve:y,reject:p}),d):(f({args:u,resolve:y,reject:p}),setTimeout(s,n),d)}}}async function os(e,t){var j,V,Y,X;const{account:r=e.account,authorizationList:n,batch:i=!!((j=e.batch)!=null&&j.multicall),blockNumber:s,blockTag:o="latest",accessList:a,blobs:c,blockOverrides:f,code:u,data:d,factory:y,factoryData:p,gas:g,gasPrice:b,maxFeePerBlobGas:E,maxFeePerGas:A,maxPriorityFeePerGas:P,nonce:w,to:_,value:T,stateOverride:I,...R}=t,L=r?ke(r):void 0;if(u&&(y||p))throw new D("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(u&&_)throw new D("Cannot provide both `code` & `to` as parameters.");const S=u&&d,$=y&&p&&_&&d,C=S||$,U=S?kw({code:u,data:d}):$?Bw({data:d,factory:y,factoryData:p,to:_}):d;try{on(t);const M=(typeof s=="bigint"?K(s):void 0)||o,B=f?bh(f):void 0,q=Au(I),W=(X=(Y=(V=e.chain)==null?void 0:V.formatters)==null?void 0:Y.transactionRequest)==null?void 0:X.format,N=(W||Yn)({...co(R,{format:W}),from:L==null?void 0:L.address,accessList:a,authorizationList:n,blobs:c,data:U,gas:g,gasPrice:b,maxFeePerBlobGas:E,maxFeePerGas:A,maxPriorityFeePerGas:P,nonce:w,to:C?void 0:_,value:T});if(i&&Tw({request:N})&&!q&&!B)try{return await Iw(e,{...N,blockNumber:s,blockTag:o})}catch(Q){if(!(Q instanceof xh)&&!(Q instanceof Hc))throw Q}const H=(()=>{const Q=[N,M];return q&&B?[...Q,q,B]:q?[...Q,q]:B?[...Q,{},B]:Q})(),Z=await e.request({method:"eth_call",params:H});return Z==="0x"?{data:void 0}:{data:Z}}catch(J){const M=Ow(J),{offchainLookup:B,offchainLookupSignature:q}=await Promise.resolve().then(()=>require("./ccip-mXBzRX9d.cjs"));if(e.ccipRead!==!1&&(M==null?void 0:M.slice(0,10))===q&&_)return{data:await B(e,{data:M,to:_})};throw C&&(M==null?void 0:M.slice(0,10))==="0x101bb98d"?new db({factory:y}):Ah(J,{...t,account:L,chain:e.chain})}}function Tw({request:e}){const{data:t,to:r,...n}=e;return!(!t||t.startsWith(xw)||!r||Object.values(n).filter(i=>typeof i<"u").length>0)}async function Iw(e,t){var b;const{batchSize:r=1024,wait:n=0}=typeof((b=e.batch)==null?void 0:b.multicall)=="object"?e.batch.multicall:{},{blockNumber:i,blockTag:s="latest",data:o,multicallAddress:a,to:c}=t;let f=a;if(!f){if(!e.chain)throw new xh;f=Xn({blockNumber:i,chain:e.chain,contract:"multicall3"})}const d=(typeof i=="bigint"?K(i):void 0)||s,{schedule:y}=_h({id:`${e.uid}.${d}`,wait:n,shouldSplitBatch(E){return E.reduce((P,{data:w})=>P+(w.length-2),0)>r*2},fn:async E=>{const A=E.map(_=>({allowFailure:!0,callData:_.data,target:_.to})),P=At({abi:$c,args:[A],functionName:"aggregate3"}),w=await e.request({method:"eth_call",params:[{data:P,to:f},d]});return an({abi:$c,args:[A],functionName:"aggregate3",data:w||"0x"})}}),[{returnData:p,success:g}]=await y({data:o,to:c});if(!g)throw new oo({data:p});return p==="0x"?{data:void 0}:{data:p}}function kw(e){const{code:t,data:r}=e;return mo({abi:ap(["constructor(bytes, bytes)"]),bytecode:Eh,args:[t,r]})}function Bw(e){const{data:t,factory:r,factoryData:n,to:i}=e;return mo({abi:ap(["constructor(address, bytes, address, bytes)"]),bytecode:Aw,args:[i,t,r,n]})}function Ow(e){var r;if(!(e instanceof D))return;const t=e.walk();return typeof(t==null?void 0:t.data)=="object"?(r=t.data)==null?void 0:r.data:t.data}async function Wt(e,t){const{abi:r,address:n,args:i,functionName:s,...o}=t,a=At({abi:r,args:i,functionName:s});try{const{data:c}=await ee(e,os,"call")({...o,data:a,to:n});return an({abi:r,args:i,functionName:s,data:c||"0x"})}catch(c){throw Jr(c,{abi:r,address:n,args:i,docsPath:"/docs/contract/readContract",functionName:s})}}async function Sh(e,t){const{abi:r,address:n,args:i,dataSuffix:s,functionName:o,...a}=t,c=a.account?ke(a.account):e.account,f=At({abi:r,args:i,functionName:o});try{const{data:u}=await ee(e,os,"call")({batch:!1,data:`${f}${s?s.replace("0x",""):""}`,to:n,...a,account:c}),d=an({abi:r,args:i,functionName:o,data:u||"0x"}),y=r.filter(p=>"name"in p&&p.name===t.functionName);return{result:d,request:{abi:y,address:n,args:i,dataSuffix:s,functionName:o,...a,account:c}}}catch(u){throw Jr(u,{abi:r,address:n,args:i,docsPath:"/docs/contract/simulateContract",functionName:o,sender:c==null?void 0:c.address})}}const Vo=new Map,rd=new Map;let Cw=0;function ur(e,t,r){const n=++Cw,i=()=>Vo.get(e)||[],s=()=>{const u=i();Vo.set(e,u.filter(d=>d.id!==n))},o=()=>{const u=i();if(!u.some(y=>y.id===n))return;const d=rd.get(e);if(u.length===1&&d){const y=d();y instanceof Promise&&y.catch(()=>{})}s()},a=i();if(Vo.set(e,[...a,{id:n,fns:t}]),a&&a.length>0)return o;const c={};for(const u in t)c[u]=(...d)=>{var p,g;const y=i();if(y.length!==0)for(const b of y)(g=(p=b.fns)[u])==null||g.call(p,...d)};const f=r(c);return typeof f=="function"&&rd.set(e,f),o}async function Lc(e){return new Promise(t=>setTimeout(t,e))}function Jn(e,{emitOnBegin:t,initialWaitTime:r,interval:n}){let i=!0;const s=()=>i=!1;return(async()=>{let a;t&&(a=await e({unpoll:s}));const c=await(r==null?void 0:r(a))??n;await Lc(c);const f=async()=>{i&&(await e({unpoll:s}),await Lc(n),f())};f()})(),s}const Rw=new Map,Nw=new Map;function Fw(e){const t=(i,s)=>({clear:()=>s.delete(i),get:()=>s.get(i),set:o=>s.set(i,o)}),r=t(e,Rw),n=t(e,Nw);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function $w(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){const n=Fw(t),i=n.response.get();if(i&&r>0&&new Date().getTime()-i.created.getTime()<r)return i.data;let s=n.promise.get();s||(s=e(),n.promise.set(s));try{const o=await s;return n.response.set({created:new Date,data:o}),o}finally{n.promise.clear()}}const Uw=e=>`blockNumber.${e}`;async function as(e,{cacheTime:t=e.cacheTime}={}){const r=await $w(()=>e.request({method:"eth_blockNumber"}),{cacheKey:Uw(e.uid),cacheTime:t});return BigInt(r)}async function go(e,{filter:t}){const r="strict"in t&&t.strict,n=await t.request({method:"eth_getFilterChanges",params:[t.id]});if(typeof n[0]=="string")return n;const i=n.map(s=>cr(s));return!("abi"in t)||!t.abi?i:Nu({abi:t.abi,logs:i,strict:r})}async function bo(e,{filter:t}){return t.request({method:"eth_uninstallFilter",params:[t.id]})}function Ph(e,t){const{abi:r,address:n,args:i,batch:s=!0,eventName:o,fromBlock:a,onError:c,onLogs:f,poll:u,pollingInterval:d=e.pollingInterval,strict:y}=t;return(typeof u<"u"?u:typeof a=="bigint"?!0:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")))?(()=>{const E=y??!1,A=Oe(["watchContractEvent",n,i,s,e.uid,o,d,E,a]);return ur(A,{onLogs:f,onError:c},P=>{let w;a!==void 0&&(w=a-1n);let _,T=!1;const I=Jn(async()=>{var R;if(!T){try{_=await ee(e,bu,"createContractEventFilter")({abi:r,address:n,args:i,eventName:o,strict:E,fromBlock:a})}catch{}T=!0;return}try{let L;if(_)L=await ee(e,go,"getFilterChanges")({filter:_});else{const S=await ee(e,as,"getBlockNumber")({});w&&w<S?L=await ee(e,$u,"getContractEvents")({abi:r,address:n,args:i,eventName:o,fromBlock:w+1n,toBlock:S,strict:E}):L=[],w=S}if(L.length===0)return;if(s)P.onLogs(L);else for(const S of L)P.onLogs([S])}catch(L){_&&L instanceof Xr&&(T=!1),(R=P.onError)==null||R.call(P,L)}},{emitOnBegin:!0,interval:d});return async()=>{_&&await ee(e,bo,"uninstallFilter")({filter:_}),I()}})})():(()=>{const E=y??!1,A=Oe(["watchContractEvent",n,i,s,e.uid,o,d,E]);let P=!0,w=()=>P=!1;return ur(A,{onLogs:f,onError:c},_=>((async()=>{try{const T=(()=>{if(e.transport.type==="fallback"){const L=e.transport.transports.find(S=>S.config.type==="webSocket"||S.config.type==="ipc");return L?L.value:e.transport}return e.transport})(),I=o?ts({abi:r,eventName:o,args:i}):[],{unsubscribe:R}=await T.subscribe({params:["logs",{address:n,topics:I}],onData(L){var $;if(!P)return;const S=L.result;try{const{eventName:C,args:U}=Ru({abi:r,data:S.data,topics:S.topics,strict:y}),j=cr(S,{args:U,eventName:C});_.onLogs([j])}catch(C){let U,j;if(C instanceof _i||C instanceof Qs){if(y)return;U=C.abiItem.name,j=($=C.abiItem.inputs)==null?void 0:$.some(Y=>!("name"in Y&&Y.name))}const V=cr(S,{args:j?[]:{},eventName:U});_.onLogs([V])}},onError(L){var S;(S=_.onError)==null||S.call(_,L)}});w=R,P||w()}catch(T){c==null||c(T)}})(),()=>w()))})()}class cn extends D{constructor({docsPath:t}={}){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(`
42
+ `),{docsPath:t,docsSlug:"account",name:"AccountNotFoundError"})}}class $s extends D{constructor({docsPath:t,metaMessages:r,type:n}){super(`Account type "${n}" is not supported.`,{docsPath:t,metaMessages:r,name:"AccountTypeNotSupportedError"})}}function Th({chain:e,currentChainId:t}){if(!e)throw new Pw;if(t!==e.id)throw new Sw({chain:e,currentChainId:t})}function Ih(e,{docsPath:t,...r}){const n=(()=>{const i=ao(e,r);return i instanceof is?e:i})();return new ob(n,{docsPath:t,...r})}async function qu(e,{serializedTransaction:t}){return e.request({method:"eth_sendRawTransaction",params:[t]},{retryCount:0})}const Wo=new no(128);async function wo(e,t){var P,w,_,T;const{account:r=e.account,chain:n=e.chain,accessList:i,authorizationList:s,blobs:o,data:a,gas:c,gasPrice:f,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:y,nonce:p,type:g,value:b,...E}=t;if(typeof r>"u")throw new cn({docsPath:"/docs/actions/wallet/sendTransaction"});const A=r?ke(r):null;try{on(t);const I=await(async()=>{if(t.to)return t.to;if(t.to!==null&&s&&s.length>0)return await Gp({authorization:s[0]}).catch(()=>{throw new D("`to` is required. Could not infer from `authorizationList`.")})})();if((A==null?void 0:A.type)==="json-rpc"||A===null){let R;n!==null&&(R=await ee(e,Zn,"getChainId")({}),Th({currentChainId:R,chain:n}));const L=(_=(w=(P=e.chain)==null?void 0:P.formatters)==null?void 0:w.transactionRequest)==null?void 0:_.format,$=(L||Yn)({...co(E,{format:L}),accessList:i,authorizationList:s,blobs:o,chainId:R,data:a,from:A==null?void 0:A.address,gas:c,gasPrice:f,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:y,nonce:p,to:I,type:g,value:b}),C=Wo.get(e.uid),U=C?"wallet_sendTransaction":"eth_sendTransaction";try{return await e.request({method:U,params:[$]},{retryCount:0})}catch(j){if(C===!1)throw j;const V=j;if(V.name==="InvalidInputRpcError"||V.name==="InvalidParamsRpcError"||V.name==="MethodNotFoundRpcError"||V.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[$]},{retryCount:0}).then(Y=>(Wo.set(e.uid,!0),Y)).catch(Y=>{const X=Y;throw X.name==="MethodNotFoundRpcError"||X.name==="MethodNotSupportedRpcError"?(Wo.set(e.uid,!1),V):X});throw V}}if((A==null?void 0:A.type)==="local"){const R=await ee(e,lo,"prepareTransactionRequest")({account:A,accessList:i,authorizationList:s,blobs:o,chain:n,data:a,gas:c,gasPrice:f,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:y,nonce:p,nonceManager:A.nonceManager,parameters:[...oh,"sidecars"],type:g,value:b,...E,to:I}),L=(T=n==null?void 0:n.serializers)==null?void 0:T.transaction,S=await A.signTransaction(R,{serializer:L});return await ee(e,qu,"sendRawTransaction")({serializedTransaction:S})}throw(A==null?void 0:A.type)==="smart"?new $s({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new $s({docsPath:"/docs/actions/wallet/sendTransaction",type:A==null?void 0:A.type})}catch(I){throw I instanceof $s?I:Ih(I,{...t,account:A,chain:t.chain||void 0})}}async function kh(e,t){const{abi:r,account:n=e.account,address:i,args:s,dataSuffix:o,functionName:a,...c}=t;if(typeof n>"u")throw new cn({docsPath:"/docs/contract/writeContract"});const f=n?ke(n):null,u=At({abi:r,args:s,functionName:a});try{return await ee(e,wo,"sendTransaction")({data:`${u}${o?o.replace("0x",""):""}`,to:i,account:f,...c})}catch(d){throw Jr(d,{abi:r,address:i,args:s,docsPath:"/docs/contract/writeContract",functionName:a,sender:f==null?void 0:f.address})}}function Ko({abi:e,address:t,client:r}){const n=r,[i,s]=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=i!=null,a=s!=null,c={};let f=!1,u=!1,d=!1;for(const y of e)if(y.type==="function"?y.stateMutability==="view"||y.stateMutability==="pure"?f=!0:u=!0:y.type==="event"&&(d=!0),f&&u&&d)break;return o&&(f&&(c.read=new Proxy({},{get(y,p){return(...g)=>{const{args:b,options:E}=bs(g);return ee(i,Wt,"readContract")({abi:e,address:t,functionName:p,args:b,...E})}}})),u&&(c.simulate=new Proxy({},{get(y,p){return(...g)=>{const{args:b,options:E}=bs(g);return ee(i,Sh,"simulateContract")({abi:e,address:t,functionName:p,args:b,...E})}}})),d&&(c.createEventFilter=new Proxy({},{get(y,p){return(...g)=>{const b=e.find(P=>P.type==="event"&&P.name===p),{args:E,options:A}=Yo(g,b);return ee(i,bu,"createContractEventFilter")({abi:e,address:t,eventName:p,args:E,...A})}}}),c.getEvents=new Proxy({},{get(y,p){return(...g)=>{const b=e.find(P=>P.type==="event"&&P.name===p),{args:E,options:A}=Yo(g,b);return ee(i,$u,"getContractEvents")({abi:e,address:t,eventName:p,args:E,...A})}}}),c.watchEvent=new Proxy({},{get(y,p){return(...g)=>{const b=e.find(P=>P.type==="event"&&P.name===p),{args:E,options:A}=Yo(g,b);return ee(i,Ph,"watchContractEvent")({abi:e,address:t,eventName:p,args:E,...A})}}}))),a&&u&&(c.write=new Proxy({},{get(y,p){return(...g)=>{const{args:b,options:E}=bs(g);return ee(s,kh,"writeContract")({abi:e,address:t,functionName:p,args:b,...E})}}})),(o||a)&&u&&(c.estimateGas=new Proxy({},{get(y,p){return(...g)=>{const{args:b,options:E}=bs(g);return ee(i??s,ch,"estimateContractGas")({abi:e,address:t,functionName:p,args:b,...E,account:E.account??s.account})}}})),c.address=t,c.abi=e,c}function bs(e){const t=e.length&&Array.isArray(e[0]),r=t?e[0]:[],n=(t?e[1]:e[0])??{};return{args:r,options:n}}function Yo(e,t){let r=!1;Array.isArray(e[0])?r=!0:e.length===1?r=t.inputs.some(s=>s.indexed):e.length===2&&(r=!0);const n=r?e[0]:void 0,i=(r?e[1]:e[0])??{};return{args:n,options:i}}const Bh={"0x0":"reverted","0x1":"success"};function Oh(e){const t={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map(r=>cr(r)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Et(e.transactionIndex):null,status:e.status?Bh[e.status]:null,type:e.type?Wp[e.type]||e.type:null};return e.blobGasPrice&&(t.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(t.blobGasUsed=BigInt(e.blobGasUsed)),t}const Hw=xu("transactionReceipt",Oh),Ch="0x5792579257925792579257925792579257925792579257925792579257925792",Rh=K(0,{size:32});async function Lw(e,t){const{account:r=e.account,capabilities:n,chain:i=e.chain,experimental_fallback:s,experimental_fallbackDelay:o=32,forceAtomic:a=!1,id:c,version:f="2.0.0"}=t,u=r?ke(r):null,d=t.calls.map(y=>{const p=y,g=p.abi?At({abi:p.abi,functionName:p.functionName,args:p.args}):p.data;return{data:p.dataSuffix&&g?ut([g,p.dataSuffix]):g,to:p.to,value:p.value?K(p.value):void 0}});try{const y=await e.request({method:"wallet_sendCalls",params:[{atomicRequired:a,calls:d,capabilities:n,chainId:K(i.id),from:u==null?void 0:u.address,id:c,version:f}]},{retryCount:0});return typeof y=="string"?{id:y}:y}catch(y){const p=y;if(s&&(p.name==="MethodNotFoundRpcError"||p.name==="MethodNotSupportedRpcError"||p.name==="UnknownRpcError"||p.details.toLowerCase().includes("does not exist / is not available")||p.details.toLowerCase().includes("missing or invalid. request()")||p.details.toLowerCase().includes("did not match any variant of untagged enum")||p.details.toLowerCase().includes("account upgraded to unsupported contract")||p.details.toLowerCase().includes("eip-7702 not supported")||p.details.toLowerCase().includes("unsupported wc_ method"))){if(n&&Object.values(n).some(P=>!P.optional)){const P="non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";throw new $n(new D(P,{details:P}))}if(a&&d.length>1){const A="`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";throw new Un(new D(A,{details:A}))}const g=[];for(const A of d){const P=wo(e,{account:u,chain:i,data:A.data,to:A.to,value:A.value?Ue(A.value):void 0});g.push(P),o>0&&await new Promise(w=>setTimeout(w,o))}const b=await Promise.allSettled(g);if(b.every(A=>A.status==="rejected"))throw b[0].reason;const E=b.map(A=>A.status==="fulfilled"?A.value:Rh);return{id:ut([...E,K(i.id,{size:32}),Ch])}}throw Ih(y,{...t,account:u,chain:t.chain})}}async function Nh(e,t){async function r(u){if(u.endsWith(Ch.slice(2))){const y=vt(Vs(u,-64,-32)),p=Vs(u,0,-64).slice(2).match(/.{1,64}/g),g=await Promise.all(p.map(E=>Rh.slice(2)!==E?e.request({method:"eth_getTransactionReceipt",params:[`0x${E}`]},{dedupe:!0}):void 0)),b=g.some(E=>E===null)?100:g.every(E=>(E==null?void 0:E.status)==="0x1")?200:g.every(E=>(E==null?void 0:E.status)==="0x0")?500:600;return{atomic:!1,chainId:Et(y),receipts:g.filter(Boolean),status:b,version:"2.0.0"}}return e.request({method:"wallet_getCallsStatus",params:[u]})}const{atomic:n=!1,chainId:i,receipts:s,version:o="2.0.0",...a}=await r(t.id),[c,f]=(()=>{const u=a.status;return u>=100&&u<200?["pending",u]:u>=200&&u<300?["success",u]:u>=300&&u<700?["failure",u]:u==="CONFIRMED"?["success",200]:u==="PENDING"?["pending",100]:[void 0,u]})();return{...a,atomic:n,chainId:i?Et(i):void 0,receipts:(s==null?void 0:s.map(u=>({...u,blockNumber:Ue(u.blockNumber),gasUsed:Ue(u.gasUsed),status:Bh[u.status]})))??[],statusCode:f,status:c,version:o}}async function Mw(e,t){const{id:r,pollingInterval:n=e.pollingInterval,status:i=({statusCode:y})=>y>=200,timeout:s=6e4}=t,o=Oe(["waitForCallsStatus",e.uid,r]),{promise:a,resolve:c,reject:f}=zu();let u;const d=ur(o,{resolve:c,reject:f},y=>{const p=Jn(async()=>{const g=b=>{clearTimeout(u),p(),b(),d()};try{const b=await Nh(e,{id:r});if(!i(b))return;g(()=>y.resolve(b))}catch(b){g(()=>y.reject(b))}},{interval:n,emitOnBegin:!0});return p});return u=s?setTimeout(()=>{d(),clearTimeout(u),f(new Dw({id:r}))},s):void 0,await a}class Dw extends D{constructor({id:t}){super(`Timed out while waiting for call bundle with id "${t}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}const Mc=256;let ws=Mc,vs;function Fh(e=11){if(!vs||ws+e>Mc*2){vs="",ws=0;for(let t=0;t<Mc;t++)vs+=(256+Math.random()*256|0).toString(16).substring(1)}return vs.substring(ws,ws+++e)}function $h(e){const{batch:t,chain:r,ccipRead:n,key:i="base",name:s="Base Client",type:o="base"}=e,a=(r==null?void 0:r.blockTime)??12e3,c=Math.min(Math.max(Math.floor(a/2),500),4e3),f=e.pollingInterval??c,u=e.cacheTime??f,d=e.account?ke(e.account):void 0,{config:y,request:p,value:g}=e.transport({chain:r,pollingInterval:f}),b={...y,...g},E={account:d,batch:t,cacheTime:u,ccipRead:n,chain:r,key:i,name:s,pollingInterval:f,request:p,transport:b,type:o,uid:Fh()};function A(P){return w=>{const _=w(P);for(const I in E)delete _[I];const T={...P,..._};return Object.assign(T,{extend:A(T)})}}return Object.assign(E,{extend:A(E)})}const Es=new no(8192);function jw(e,{enabled:t=!0,id:r}){if(!t||!r)return e();if(Es.get(r))return Es.get(r);const n=e().finally(()=>Es.delete(r));return Es.set(r,n),n}function Dc(e,{delay:t=100,retryCount:r=2,shouldRetry:n=()=>!0}={}){return new Promise((i,s)=>{const o=async({count:a=0}={})=>{const c=async({error:f})=>{const u=typeof t=="function"?t({count:a,error:f}):t;u&&await Lc(u),o({count:a+1})};try{const f=await e();i(f)}catch(f){if(a<r&&await n({count:a,error:f}))return c({error:f});s(f)}};o()})}function zw(e,t={}){return async(r,n={})=>{var d;const{dedupe:i=!1,methods:s,retryDelay:o=150,retryCount:a=3,uid:c}={...t,...n},{method:f}=r;if((d=s==null?void 0:s.exclude)!=null&&d.includes(f))throw new Lr(new Error("method not supported"),{method:f});if(s!=null&&s.include&&!s.include.includes(f))throw new Lr(new Error("method not supported"),{method:f});const u=i?Rn(`${c}.${Oe(r)}`):void 0;return jw(()=>Dc(async()=>{try{return await e(r)}catch(y){const p=y;switch(p.code){case Ii.code:throw new Ii(p);case ki.code:throw new ki(p);case Bi.code:throw new Bi(p,{method:r.method});case Oi.code:throw new Oi(p);case Zr.code:throw new Zr(p);case Xr.code:throw new Xr(p);case Ci.code:throw new Ci(p);case Ri.code:throw new Ri(p);case Ni.code:throw new Ni(p);case Lr.code:throw new Lr(p,{method:r.method});case Fn.code:throw new Fn(p);case Fi.code:throw new Fi(p);case Tn.code:throw new Tn(p);case $i.code:throw new $i(p);case Ui.code:throw new Ui(p);case Hi.code:throw new Hi(p);case Li.code:throw new Li(p);case Mi.code:throw new Mi(p);case $n.code:throw new $n(p);case Di.code:throw new Di(p);case ji.code:throw new ji(p);case zi.code:throw new zi(p);case qi.code:throw new qi(p);case Gi.code:throw new Gi(p);case Un.code:throw new Un(p);case 5e3:throw new Tn(p);default:throw y instanceof D?y:new pb(p)}}},{delay:({count:y,error:p})=>{var g;if(p&&p instanceof Pn){const b=(g=p==null?void 0:p.headers)==null?void 0:g.get("Retry-After");if(b!=null&&b.match(/\d/))return Number.parseInt(b)*1e3}return~~(1<<y)*o},retryCount:a,shouldRetry:({error:y})=>qw(y)}),{enabled:i,id:u})}}function qw(e){return"code"in e&&typeof e.code=="number"?e.code===-1||e.code===Fn.code||e.code===Zr.code:e instanceof Pn&&e.status?e.status===403||e.status===408||e.status===413||e.status===429||e.status===500||e.status===502||e.status===503||e.status===504:!0}function Uh({key:e,methods:t,name:r,request:n,retryCount:i=3,retryDelay:s=150,timeout:o,type:a},c){const f=Fh();return{config:{key:e,methods:t,name:r,request:n,retryCount:i,retryDelay:s,timeout:o,type:a},request:zw(n,{methods:t,retryCount:i,retryDelay:s,uid:f}),value:c}}function nd(e,t={}){const{key:r="custom",methods:n,name:i="Custom Provider",retryDelay:s}=t;return({retryCount:o})=>Uh({key:r,methods:n,name:i,request:e.request.bind(e),retryCount:t.retryCount??o,retryDelay:s,type:"custom"})}class Gw extends D{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(e,{errorInstance:t=new Error("timed out"),timeout:r,signal:n}){return new Promise((i,s)=>{(async()=>{let o;try{const a=new AbortController;r>0&&(o=setTimeout(()=>{n&&a.abort()},r)),i(await e({signal:(a==null?void 0:a.signal)||null}))}catch(a){(a==null?void 0:a.name)==="AbortError"&&s(t),s(a)}finally{clearTimeout(o)}})()})}function Ww(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const id=Ww();function Kw(e,t={}){return{async request(r){var d;const{body:n,onRequest:i=t.onRequest,onResponse:s=t.onResponse,timeout:o=t.timeout??1e4}=r,a={...t.fetchOptions??{},...r.fetchOptions??{}},{headers:c,method:f,signal:u}=a;try{const y=await Vw(async({signal:g})=>{const b={...a,body:Array.isArray(n)?Oe(n.map(w=>({jsonrpc:"2.0",id:w.id??id.take(),...w}))):Oe({jsonrpc:"2.0",id:n.id??id.take(),...n}),headers:{"Content-Type":"application/json",...c},method:f||"POST",signal:u||(o>0?g:null)},E=new Request(e,b),A=await(i==null?void 0:i(E,b))??{...b,url:e};return await fetch(A.url??e,A)},{errorInstance:new Df({body:n,url:e}),timeout:o,signal:!0});s&&await s(y);let p;if((d=y.headers.get("Content-Type"))!=null&&d.startsWith("application/json"))p=await y.json();else{p=await y.text();try{p=JSON.parse(p||"{}")}catch(g){if(y.ok)throw g;p={error:p}}}if(!y.ok)throw new Pn({body:n,details:Oe(p.error)||y.statusText,headers:y.headers,status:y.status,url:e});return p}catch(y){throw y instanceof Pn||y instanceof Df?y:new Pn({body:n,cause:y,url:e})}}}}function Hh(e,t={}){const{batch:r,fetchOptions:n,key:i="http",methods:s,name:o="HTTP JSON-RPC",onFetchRequest:a,onFetchResponse:c,retryDelay:f,raw:u}=t;return({chain:d,retryCount:y,timeout:p})=>{const{batchSize:g=1e3,wait:b=0}=typeof r=="object"?r:{},E=t.retryCount??y,A=p??t.timeout??1e4,P=d==null?void 0:d.rpcUrls.default.http[0];if(!P)throw new Gw;const w=Kw(P,{fetchOptions:n,onRequest:a,onResponse:c,timeout:A});return Uh({key:i,methods:s,name:o,async request({method:_,params:T}){const I={method:_,params:T},{schedule:R}=_h({id:P,wait:b,shouldSplitBatch(C){return C.length>g},fn:C=>w.request({body:C}),sort:(C,U)=>C.id-U.id}),L=async C=>r?R(C):[await w.request({body:C})],[{error:S,result:$}]=await L(I);if(u)return{error:S,result:$};if(S)throw new Eu({body:I,error:S,url:P});return $},retryCount:E,retryDelay:f,timeout:A,type:"http"},{fetchOptions:n,url:P})}}function Gu(e,t){var n,i,s,o,a,c;if(!(e instanceof D))return!1;const r=e.walk(f=>f instanceof Sc);return r instanceof Sc?!!(((n=r.data)==null?void 0:n.errorName)==="ResolverNotFound"||((i=r.data)==null?void 0:i.errorName)==="ResolverWildcardNotSupported"||((s=r.data)==null?void 0:s.errorName)==="ResolverNotContract"||((o=r.data)==null?void 0:o.errorName)==="ResolverError"||((a=r.data)==null?void 0:a.errorName)==="HttpError"||(c=r.reason)!=null&&c.includes("Wildcard on non-extended resolvers is not supported")||t==="reverse"&&r.reason===Rp[50]):!1}function Yw(e){const{abi:t,data:r}=e,n=Yr(r,0,4),i=t.find(s=>s.type==="function"&&n===es(Tt(s)));if(!i)throw new $m(n,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:i.name,args:"inputs"in i&&i.inputs&&i.inputs.length>0?rs(i.inputs,Yr(r,4)):void 0}}const Zo="/docs/contract/encodeErrorResult";function sd(e){const{abi:t,errorName:r,args:n}=e;let i=t[0];if(r){const c=sn({abi:t,args:n,name:r});if(!c)throw new Pf(r,{docsPath:Zo});i=c}if(i.type!=="error")throw new Pf(void 0,{docsPath:Zo});const s=Tt(i),o=es(s);let a="0x";if(n&&n.length>0){if(!i.inputs)throw new Nm(i.name,{docsPath:Zo});a=pr(i.inputs,n)}return Ct([o,a])}const Xo="/docs/contract/encodeFunctionResult";function Zw(e){const{abi:t,functionName:r,result:n}=e;let i=t[0];if(r){const o=sn({abi:t,name:r});if(!o)throw new Cn(r,{docsPath:Xo});i=o}if(i.type!=="function")throw new Cn(void 0,{docsPath:Xo});if(!i.outputs)throw new pp(i.name,{docsPath:Xo});const s=(()=>{if(i.outputs.length===0)return[];if(i.outputs.length===1)return[n];if(Array.isArray(n))return n;throw new hp(n)})();return pr(i.outputs,s)}const vo="x-batch-gateway:true";async function Lh(e){const{data:t,ccipRequest:r}=e,{args:[n]}=Yw({abi:Uc,data:t}),i=[],s=[];return await Promise.all(n.map(async(o,a)=>{try{s[a]=o.urls.includes(vo)?await Lh({data:o.data,ccipRequest:r}):await r(o),i[a]=!1}catch(c){i[a]=!0,s[a]=Xw(c)}})),Zw({abi:Uc,functionName:"query",result:[i,s]})}function Xw(e){return e.name==="HttpRequestError"&&e.status?sd({abi:Uc,errorName:"HttpError",args:[e.status,e.shortMessage]}):sd({abi:[Np],errorName:"Error",args:["shortMessage"in e?e.shortMessage:e.message]})}function Mh(e){if(e.length!==66||e.indexOf("[")!==0||e.indexOf("]")!==65)return null;const t=`0x${e.slice(1,65)}`;return It(t)?t:null}function Us(e){let t=new Uint8Array(32).fill(0);if(!e)return Ce(t);const r=e.split(".");for(let n=r.length-1;n>=0;n-=1){const i=Mh(r[n]),s=i?Kn(i):De(zr(r[n]),"bytes");t=De(ut([t,s]),"bytes")}return Ce(t)}function Jw(e){return`[${e.slice(2)}]`}function Qw(e){const t=new Uint8Array(32).fill(0);return e?Mh(e)||De(zr(e)):Ce(t)}function Eo(e){const t=e.replace(/^\.|\.$/gm,"");if(t.length===0)return new Uint8Array(1);const r=new Uint8Array(zr(t).byteLength+2);let n=0;const i=t.split(".");for(let s=0;s<i.length;s++){let o=zr(i[s]);o.byteLength>255&&(o=zr(Jw(Qw(i[s])))),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 e1(e,t){const{blockNumber:r,blockTag:n,coinType:i,name:s,gatewayUrls:o,strict:a}=t,{chain:c}=e,f=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Xn({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),u=c==null?void 0:c.ensTlds;if(u&&!u.some(d=>s.endsWith(d)))return null;try{const d=At({abi:ed,functionName:"addr",...i!=null?{args:[Us(s),BigInt(i)]}:{args:[Us(s)]}}),y={address:f,abi:vh,functionName:"resolve",args:[je(Eo(s)),d,o??[vo]],blockNumber:r,blockTag:n},g=await ee(e,Wt,"readContract")(y);if(g[0]==="0x")return null;const b=an({abi:ed,args:i!=null?[Us(s),BigInt(i)]:void 0,functionName:"addr",data:g[0]});return b==="0x"||vt(b)==="0x00"?null:b}catch(d){if(a)throw d;if(Gu(d,"resolve"))return null;throw d}}class t1 extends D{constructor({data:t}){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(t)}`],name:"EnsAvatarInvalidMetadataError"})}}class ni extends D{constructor({reason:t}){super(`ENS NFT avatar URI is invalid. ${t}`,{name:"EnsAvatarInvalidNftUriError"})}}class Vu extends D{constructor({uri:t}){super(`Unable to resolve ENS avatar URI "${t}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class r1 extends D{constructor({namespace:t}){super(`ENS NFT avatar namespace "${t}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}const n1=/(?<protocol>https?:\/\/[^\/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,i1=/^(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>\/.*)?$/,s1=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,o1=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function a1(e){try{const t=await fetch(e,{method:"HEAD"});if(t.status===200){const r=t.headers.get("content-type");return r==null?void 0:r.startsWith("image/")}return!1}catch(t){return typeof t=="object"&&typeof t.response<"u"||!globalThis.hasOwnProperty("Image")?!1:new Promise(r=>{const n=new Image;n.onload=()=>{r(!0)},n.onerror=()=>{r(!1)},n.src=e})}}function od(e,t){return e?e.endsWith("/")?e.slice(0,-1):e:t}function Dh({uri:e,gatewayUrls:t}){const r=s1.test(e);if(r)return{uri:e,isOnChain:!0,isEncoded:r};const n=od(t==null?void 0:t.ipfs,"https://ipfs.io"),i=od(t==null?void 0:t.arweave,"https://arweave.net"),s=e.match(n1),{protocol:o,subpath:a,target:c,subtarget:f=""}=(s==null?void 0:s.groups)||{},u=o==="ipns:/"||a==="ipns/",d=o==="ipfs:/"||a==="ipfs/"||i1.test(e);if(e.startsWith("http")&&!u&&!d){let p=e;return t!=null&&t.arweave&&(p=e.replace(/https:\/\/arweave.net/g,t==null?void 0:t.arweave)),{uri:p,isOnChain:!1,isEncoded:!1}}if((u||d)&&c)return{uri:`${n}/${u?"ipns":"ipfs"}/${c}${f}`,isOnChain:!1,isEncoded:!1};if(o==="ar:/"&&c)return{uri:`${i}/${c}${f||""}`,isOnChain:!1,isEncoded:!1};let y=e.replace(o1,"");if(y.startsWith("<svg")&&(y=`data:image/svg+xml;base64,${btoa(y)}`),y.startsWith("data:")||y.startsWith("{"))return{uri:y,isOnChain:!0,isEncoded:!1};throw new Vu({uri:e})}function jh(e){if(typeof e!="object"||!("image"in e)&&!("image_url"in e)&&!("image_data"in e))throw new t1({data:e});return e.image||e.image_url||e.image_data}async function c1({gatewayUrls:e,uri:t}){try{const r=await fetch(t).then(i=>i.json());return await Wu({gatewayUrls:e,uri:jh(r)})}catch{throw new Vu({uri:t})}}async function Wu({gatewayUrls:e,uri:t}){const{uri:r,isOnChain:n}=Dh({uri:t,gatewayUrls:e});if(n||await a1(r))return r;throw new Vu({uri:t})}function u1(e){let t=e;t.startsWith("did:nft:")&&(t=t.replace("did:nft:","").replace(/_/g,"/"));const[r,n,i]=t.split("/"),[s,o]=r.split(":"),[a,c]=n.split(":");if(!s||s.toLowerCase()!=="eip155")throw new ni({reason:"Only EIP-155 supported"});if(!o)throw new ni({reason:"Chain ID not found"});if(!c)throw new ni({reason:"Contract address not found"});if(!i)throw new ni({reason:"Token ID not found"});if(!a)throw new ni({reason:"ERC namespace not found"});return{chainID:Number.parseInt(o),namespace:a.toLowerCase(),contractAddress:c,tokenID:i}}async function f1(e,{nft:t}){if(t.namespace==="erc721")return Wt(e,{address:t.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(t.tokenID)]});if(t.namespace==="erc1155")return Wt(e,{address:t.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(t.tokenID)]});throw new r1({namespace:t.namespace})}async function d1(e,{gatewayUrls:t,record:r}){return/eip155:/i.test(r)?l1(e,{gatewayUrls:t,record:r}):Wu({uri:r,gatewayUrls:t})}async function l1(e,{gatewayUrls:t,record:r}){const n=u1(r),i=await f1(e,{nft:n}),{uri:s,isOnChain:o,isEncoded:a}=Dh({uri:i,gatewayUrls:t});if(o&&(s.includes("data:application/json;base64,")||s.startsWith("{"))){const f=a?atob(s.replace("data:application/json;base64,","")):s,u=JSON.parse(f);return Wu({uri:jh(u),gatewayUrls:t})}let c=n.tokenID;return n.namespace==="erc1155"&&(c=c.replace("0x","").padStart(64,"0")),c1({gatewayUrls:t,uri:s.replace(/(?:0x)?{id}/,c)})}async function zh(e,t){const{blockNumber:r,blockTag:n,key:i,name:s,gatewayUrls:o,strict:a}=t,{chain:c}=e,f=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Xn({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),u=c==null?void 0:c.ensTlds;if(u&&!u.some(d=>s.endsWith(d)))return null;try{const d={address:f,abi:vh,functionName:"resolve",args:[je(Eo(s)),At({abi:Qf,functionName:"text",args:[Us(s),i]}),o??[vo]],blockNumber:r,blockTag:n},p=await ee(e,Wt,"readContract")(d);if(p[0]==="0x")return null;const g=an({abi:Qf,functionName:"text",data:p[0]});return g===""?null:g}catch(d){if(a)throw d;if(Gu(d,"resolve"))return null;throw d}}async function p1(e,{blockNumber:t,blockTag:r,assetGatewayUrls:n,name:i,gatewayUrls:s,strict:o,universalResolverAddress:a}){const c=await ee(e,zh,"getEnsText")({blockNumber:t,blockTag:r,key:"avatar",name:i,universalResolverAddress:a,gatewayUrls:s,strict:o});if(!c)return null;try{return await d1(e,{record:c,gatewayUrls:n})}catch{return null}}async function h1(e,{address:t,blockNumber:r,blockTag:n,gatewayUrls:i,strict:s,universalResolverAddress:o}){let a=o;if(!a){if(!e.chain)throw new Error("client chain not configured. universalResolverAddress is required.");a=Xn({blockNumber:r,chain:e.chain,contract:"ensUniversalResolver"})}const c=`${t.toLowerCase().substring(2)}.addr.reverse`;try{const f={address:a,abi:Ew,functionName:"reverse",args:[je(Eo(c))],blockNumber:r,blockTag:n},u=ee(e,Wt,"readContract"),[d,y]=i?await u({...f,args:[...f.args,i]}):await u(f);return t.toLowerCase()!==y.toLowerCase()?null:d}catch(f){if(s)throw f;if(Gu(f,"reverse"))return null;throw f}}async function y1(e,t){const{blockNumber:r,blockTag:n,name:i}=t,{chain:s}=e,o=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!s)throw new Error("client chain not configured. universalResolverAddress is required.");return Xn({blockNumber:r,chain:s,contract:"ensUniversalResolver"})})(),a=s==null?void 0:s.ensTlds;if(a&&!a.some(f=>i.endsWith(f)))throw new Error(`${i} is not a valid ENS TLD (${a==null?void 0:a.join(", ")}) for chain "${s.name}" (id: ${s.id}).`);const[c]=await ee(e,Wt,"readContract")({address:o,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[je(Eo(i))],blockNumber:r,blockTag:n});return c}async function qh(e,t){var E,A,P;const{account:r=e.account,blockNumber:n,blockTag:i="latest",blobs:s,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:f,maxFeePerGas:u,maxPriorityFeePerGas:d,to:y,value:p,...g}=t,b=r?ke(r):void 0;try{on(t);const _=(typeof n=="bigint"?K(n):void 0)||i,T=(P=(A=(E=e.chain)==null?void 0:E.formatters)==null?void 0:A.transactionRequest)==null?void 0:P.format,R=(T||Yn)({...co(g,{format:T}),from:b==null?void 0:b.address,blobs:s,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:f,maxFeePerGas:u,maxPriorityFeePerGas:d,to:y,value:p}),L=await e.request({method:"eth_createAccessList",params:[R,_]});return{accessList:L.accessList,gasUsed:BigInt(L.gasUsed)}}catch(w){throw Ah(w,{...t,account:b,chain:e.chain})}}async function m1(e){const t=io(e,{method:"eth_newBlockFilter"}),r=await e.request({method:"eth_newBlockFilter"});return{id:r,request:t(r),type:"block"}}async function Gh(e,{address:t,args:r,event:n,events:i,fromBlock:s,strict:o,toBlock:a}={}){const c=i??(n?[n]:void 0),f=io(e,{method:"eth_newFilter"});let u=[];c&&(u=[c.flatMap(p=>ts({abi:[p],eventName:p.name,args:r}))],n&&(u=u[0]));const d=await e.request({method:"eth_newFilter",params:[{address:t,fromBlock:typeof s=="bigint"?K(s):s,toBlock:typeof a=="bigint"?K(a):a,...u.length?{topics:u}:{}}]});return{abi:c,args:r,eventName:n?n.name:void 0,fromBlock:s,id:d,request:f(d),strict:!!o,toBlock:a,type:"event"}}async function Vh(e){const t=io(e,{method:"eth_newPendingTransactionFilter"}),r=await e.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:t(r),type:"transaction"}}async function g1(e){const t=await e.request({method:"eth_blobBaseFee"});return BigInt(t)}async function b1(e,{blockHash:t,blockNumber:r,blockTag:n="latest"}={}){const i=r!==void 0?K(r):void 0;let s;return t?s=await e.request({method:"eth_getBlockTransactionCountByHash",params:[t]},{dedupe:!0}):s=await e.request({method:"eth_getBlockTransactionCountByNumber",params:[i||n]},{dedupe:!!i}),Et(s)}async function ad(e,{address:t,blockNumber:r,blockTag:n="latest"}){const i=r!==void 0?K(r):void 0,s=await e.request({method:"eth_getCode",params:[t,i||n]},{dedupe:!!i});if(s!=="0x")return s}class w1 extends D{constructor({address:t}){super(`No EIP-712 domain found on contract "${t}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${t}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}async function v1(e,t){const{address:r,factory:n,factoryData:i}=t;try{const[s,o,a,c,f,u,d]=await ee(e,Wt,"readContract")({abi:E1,address:r,functionName:"eip712Domain",factory:n,factoryData:i});return{domain:{name:o,version:a,chainId:Number(c),verifyingContract:f,salt:u},extensions:d,fields:s}}catch(s){const o=s;throw o.name==="ContractFunctionExecutionError"&&o.cause.name==="ContractFunctionZeroDataError"?new w1({address:r}):o}}const E1=[{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 x1(e){var t;return{baseFeePerGas:e.baseFeePerGas.map(r=>BigInt(r)),gasUsedRatio:e.gasUsedRatio,oldestBlock:BigInt(e.oldestBlock),reward:(t=e.reward)==null?void 0:t.map(r=>r.map(n=>BigInt(n)))}}async function A1(e,{blockCount:t,blockNumber:r,blockTag:n="latest",rewardPercentiles:i}){const s=typeof r=="bigint"?K(r):void 0,o=await e.request({method:"eth_feeHistory",params:[K(t),s||n,i]},{dedupe:!!s});return x1(o)}async function _1(e,{filter:t}){const r=t.strict??!1,i=(await t.request({method:"eth_getFilterLogs",params:[t.id]})).map(s=>cr(s));return t.abi?Nu({abi:t.abi,logs:i,strict:r}):i}function ot(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}class S1 extends D{constructor({domain:t}){super(`Invalid domain "${Oe(t)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class P1 extends D{constructor({primaryType:t,types:r}){super(`Invalid primary type \`${t}\` 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 T1 extends D{constructor({type:t}){super(`Struct type "${t}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}function I1(e){const{domain:t={},message:r,primaryType:n}=e,i={EIP712Domain:Jh({domain:t}),...e.types};Xh({domain:t,message:r,primaryType:n,types:i});const s=["0x1901"];return t&&s.push(k1({domain:t,types:i})),n!=="EIP712Domain"&&s.push(Wh({data:r,primaryType:n,types:i})),De(ut(s))}function k1({domain:e,types:t}){return Wh({data:e,primaryType:"EIP712Domain",types:t})}function Wh({data:e,primaryType:t,types:r}){const n=Kh({data:e,primaryType:t,types:r});return De(n)}function Kh({data:e,primaryType:t,types:r}){const n=[{type:"bytes32"}],i=[B1({primaryType:t,types:r})];for(const s of r[t]){const[o,a]=Zh({types:r,name:s.name,type:s.type,value:e[s.name]});n.push(o),i.push(a)}return pr(n,i)}function B1({primaryType:e,types:t}){const r=je(O1({primaryType:e,types:t}));return De(r)}function O1({primaryType:e,types:t}){let r="";const n=Yh({primaryType:e,types:t});n.delete(e);const i=[e,...Array.from(n).sort()];for(const s of i)r+=`${s}(${t[s].map(({name:o,type:a})=>`${a} ${o}`).join(",")})`;return r}function Yh({primaryType:e,types:t},r=new Set){const n=e.match(/^\w*/u),i=n==null?void 0:n[0];if(r.has(i)||t[i]===void 0)return r;r.add(i);for(const s of t[i])Yh({primaryType:s.type,types:t},r);return r}function Zh({types:e,name:t,type:r,value:n}){if(e[r]!==void 0)return[{type:"bytes32"},De(Kh({data:n,primaryType:r,types:e}))];if(r==="bytes")return n=`0x${(n.length%2?"0":"")+n.slice(2)}`,[{type:"bytes32"},De(n)];if(r==="string")return[{type:"bytes32"},De(je(n))];if(r.lastIndexOf("]")===r.length-1){const i=r.slice(0,r.lastIndexOf("[")),s=n.map(o=>Zh({name:t,type:i,types:e,value:o}));return[{type:"bytes32"},De(pr(s.map(([o])=>o),s.map(([,o])=>o)))]}return[{type:r},n]}function C1(e){const{domain:t,message:r,primaryType:n,types:i}=e,s=(c,f)=>{const u={...f};for(const d of c){const{name:y,type:p}=d;p==="address"&&(u[y]=u[y].toLowerCase())}return u},o=i.EIP712Domain?t?s(i.EIP712Domain,t):{}:{},a=(()=>{if(n!=="EIP712Domain")return s(i[n],r)})();return Oe({domain:o,message:a,primaryType:n,types:i})}function Xh(e){const{domain:t,message:r,primaryType:n,types:i}=e,s=(o,a)=>{for(const c of o){const{name:f,type:u}=c,d=a[f],y=u.match(Op);if(y&&(typeof d=="number"||typeof d=="bigint")){const[b,E,A]=y;K(d,{signed:E==="int",size:Number.parseInt(A)/8})}if(u==="address"&&typeof d=="string"&&!Fe(d))throw new tt({address:d});const p=u.match(Ig);if(p){const[b,E]=p;if(E&&Se(d)!==Number.parseInt(E))throw new Hm({expectedSize:Number.parseInt(E),givenSize:Se(d)})}const g=i[u];g&&(R1(u),s(g,d))}};if(i.EIP712Domain&&t){if(typeof t!="object")throw new S1({domain:t});s(i.EIP712Domain,t)}if(n!=="EIP712Domain")if(i[n])s(i[n],r);else throw new P1({primaryType:n,types:i})}function Jh({domain:e}){return[typeof(e==null?void 0:e.name)=="string"&&{name:"name",type:"string"},(e==null?void 0:e.version)&&{name:"version",type:"string"},(typeof(e==null?void 0:e.chainId)=="number"||typeof(e==null?void 0:e.chainId)=="bigint")&&{name:"chainId",type:"uint256"},(e==null?void 0:e.verifyingContract)&&{name:"verifyingContract",type:"address"},(e==null?void 0:e.salt)&&{name:"salt",type:"bytes32"}].filter(Boolean)}function R1(e){if(e==="address"||e==="bool"||e==="string"||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new T1({type:e})}function N1(e){const{authorizationList:t}=e;if(t)for(const r of t){const{chainId:n}=r,i=r.address;if(!Fe(i))throw new tt({address:i});if(n<0)throw new yo({chainId:n})}Ku(e)}function F1(e){const{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new nh;for(const r of t){const n=Se(r),i=Et(Yr(r,0,1));if(n!==32)throw new zb({hash:r,size:n});if(i!==rh)throw new qb({hash:r,version:i})}}Ku(e)}function Ku(e){const{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:i}=e;if(t<=0)throw new yo({chainId:t});if(i&&!Fe(i))throw new tt({address:i});if(n&&n>uo)throw new Qr({maxFeePerGas:n});if(r&&n&&r>n)throw new Vi({maxFeePerGas:n,maxPriorityFeePerGas:r})}function $1(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:s}=e;if(t<=0)throw new yo({chainId:t});if(s&&!Fe(s))throw new tt({address:s});if(r||i)throw new D("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>uo)throw new Qr({maxFeePerGas:n})}function U1(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:s}=e;if(s&&!Fe(s))throw new tt({address:s});if(typeof t<"u"&&t<=0)throw new yo({chainId:t});if(r||i)throw new D("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>uo)throw new Qr({maxFeePerGas:n})}function xo(e){if(!e||e.length===0)return[];const t=[];for(let r=0;r<e.length;r++){const{address:n,storageKeys:i}=e[r];for(let s=0;s<i.length;s++)if(i[s].length-2!==64)throw new sb({storageKey:i[s]});if(!Fe(n,{strict:!1}))throw new tt({address:n});t.push([n,i])}return t}function H1(e,t){const r=sh(e);return r==="eip1559"?D1(e,t):r==="eip2930"?j1(e,t):r==="eip4844"?M1(e,t):r==="eip7702"?L1(e,t):z1(e,t)}function L1(e,t){const{authorizationList:r,chainId:n,gas:i,nonce:s,to:o,value:a,maxFeePerGas:c,maxPriorityFeePerGas:f,accessList:u,data:d}=e;N1(e);const y=xo(u),p=q1(r);return Ct(["0x04",Cr([K(n),s?K(s):"0x",f?K(f):"0x",c?K(c):"0x",i?K(i):"0x",o??"0x",a?K(a):"0x",d??"0x",y,p,...cs(e,t)])])}function M1(e,t){const{chainId:r,gas:n,nonce:i,to:s,value:o,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:f,accessList:u,data:d}=e;F1(e);let y=e.blobVersionedHashes,p=e.sidecars;if(e.blobs&&(typeof y>"u"||typeof p>"u")){const w=typeof e.blobs[0]=="string"?e.blobs:e.blobs.map(I=>Ce(I)),_=e.kzg,T=Iu({blobs:w,kzg:_});if(typeof y>"u"&&(y=Qp({commitments:T})),typeof p>"u"){const I=ku({blobs:w,commitments:T,kzg:_});p=ih({blobs:w,commitments:T,proofs:I})}}const g=xo(u),b=[K(r),i?K(i):"0x",f?K(f):"0x",c?K(c):"0x",n?K(n):"0x",s??"0x",o?K(o):"0x",d??"0x",g,a?K(a):"0x",y??[],...cs(e,t)],E=[],A=[],P=[];if(p)for(let w=0;w<p.length;w++){const{blob:_,commitment:T,proof:I}=p[w];E.push(_),A.push(T),P.push(I)}return Ct(["0x03",Cr(p?[b,E,A,P]:b)])}function D1(e,t){const{chainId:r,gas:n,nonce:i,to:s,value:o,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:f,data:u}=e;Ku(e);const d=xo(f),y=[K(r),i?K(i):"0x",c?K(c):"0x",a?K(a):"0x",n?K(n):"0x",s??"0x",o?K(o):"0x",u??"0x",d,...cs(e,t)];return Ct(["0x02",Cr(y)])}function j1(e,t){const{chainId:r,gas:n,data:i,nonce:s,to:o,value:a,accessList:c,gasPrice:f}=e;$1(e);const u=xo(c),d=[K(r),s?K(s):"0x",f?K(f):"0x",n?K(n):"0x",o??"0x",a?K(a):"0x",i??"0x",u,...cs(e,t)];return Ct(["0x01",Cr(d)])}function z1(e,t){const{chainId:r=0,gas:n,data:i,nonce:s,to:o,value:a,gasPrice:c}=e;U1(e);let f=[s?K(s):"0x",c?K(c):"0x",n?K(n):"0x",o??"0x",a?K(a):"0x",i??"0x"];if(t){const u=(()=>{if(t.v>=35n)return(t.v-35n)/2n>0?t.v:27n+(t.v===35n?0n:1n);if(r>0)return BigInt(r*2)+BigInt(35n+t.v-27n);const p=27n+(t.v===27n?0n:1n);if(t.v!==p)throw new nb({v:t.v});return p})(),d=vt(t.r),y=vt(t.s);f=[...f,K(u),d==="0x00"?"0x":d,y==="0x00"?"0x":y]}else r>0&&(f=[...f,K(r),"0x","0x"]);return Cr(f)}function cs(e,t){const r=t??e,{v:n,yParity:i}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof i>"u")return[];const s=vt(r.r),o=vt(r.s);return[typeof i=="number"?i?K(1):"0x":n===0n?"0x":n===1n?K(1):n===27n?"0x":K(1),s==="0x00"?"0x":s,o==="0x00"?"0x":o]}function q1(e){if(!e||e.length===0)return[];const t=[];for(const r of e){const{chainId:n,nonce:i,...s}=r,o=r.address;t.push([n?je(n):"0x",o,i?je(i):"0x",...cs({},s)])}return t}const G1=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Qh=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),V1=Qh.map(e=>(9*e+5)%16),e0=(()=>{const r=[[Qh],[V1]];for(let n=0;n<4;n++)for(let i of r)i.push(i[n].map(s=>G1[s]));return r})(),t0=e0[0],r0=e0[1],n0=[[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(e=>Uint8Array.from(e)),W1=t0.map((e,t)=>e.map(r=>n0[t][r])),K1=r0.map((e,t)=>e.map(r=>n0[t][r])),Y1=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Z1=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function cd(e,t,r,n){return e===0?t^r^n:e===1?t&r|~t&n:e===2?(t|~r)^n:e===3?t&n|r&~n:t^(r|~n)}const xs=new Uint32Array(16);let i0=class extends Yp{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:t,h1:r,h2:n,h3:i,h4:s}=this;return[t,r,n,i,s]}set(t,r,n,i,s){this.h0=t|0,this.h1=r|0,this.h2=n|0,this.h3=i|0,this.h4=s|0}process(t,r){for(let p=0;p<16;p++,r+=4)xs[p]=t.getUint32(r,!0);let n=this.h0|0,i=n,s=this.h1|0,o=s,a=this.h2|0,c=a,f=this.h3|0,u=f,d=this.h4|0,y=d;for(let p=0;p<5;p++){const g=4-p,b=Y1[p],E=Z1[p],A=t0[p],P=r0[p],w=W1[p],_=K1[p];for(let T=0;T<16;T++){const I=ms(n+cd(p,s,a,f)+xs[A[T]]+b,w[T])+d|0;n=d,d=f,f=ms(a,10)|0,a=s,s=I}for(let T=0;T<16;T++){const I=ms(i+cd(g,o,c,u)+xs[P[T]]+E,_[T])+y|0;i=y,y=u,u=ms(c,10)|0,c=o,o=I}}this.set(this.h1+a+u|0,this.h2+f+y|0,this.h3+d+i|0,this.h4+n+o|0,this.h0+s+c|0)}roundClean(){Or(xs)}destroy(){this.destroyed=!0,Or(this.buffer),this.set(0,0,0,0,0)}};const X1=to(()=>new i0),J1=i0,Q1=X1,e2=Object.freeze(Object.defineProperty({__proto__:null,RIPEMD160:J1,ripemd160:Q1},Symbol.toStringTag,{value:"Module"})),t2=`Ethereum Signed Message:
43
+ `;function r2(e){const t=typeof e=="string"?Rn(e):typeof e.raw=="string"?e.raw:Ce(e.raw),r=Rn(`${t2}${Se(t)}`);return ut([r,t])}function s0(e,t){return De(r2(e),t)}const o0="0x6492649264926492649264926492649264926492649264926492649264926492";function n2(e){return Vs(e,-32)===o0}function i2(e){const{address:t,data:r,signature:n,to:i="hex"}=e,s=Ct([pr([{type:"address"},{type:"bytes"},{type:"bytes"}],[t,r,n]),o0]);return i==="hex"?s:kt(s)}function s2(e){return e.map(t=>({...t,value:BigInt(t.value)}))}function o2(e){return{...e,balance:e.balance?BigInt(e.balance):void 0,nonce:e.nonce?Et(e.nonce):void 0,storageProof:e.storageProof?s2(e.storageProof):void 0}}async function a2(e,{address:t,blockNumber:r,blockTag:n,storageKeys:i}){const s=n??"latest",o=r!==void 0?K(r):void 0,a=await e.request({method:"eth_getProof",params:[t,i,o||s]});return o2(a)}async function c2(e,{address:t,blockNumber:r,blockTag:n="latest",slot:i}){const s=r!==void 0?K(r):void 0;return await e.request({method:"eth_getStorageAt",params:[t,i,s||n]})}async function Yu(e,{blockHash:t,blockNumber:r,blockTag:n,hash:i,index:s}){var u,d,y;const o=n||"latest",a=r!==void 0?K(r):void 0;let c=null;if(i?c=await e.request({method:"eth_getTransactionByHash",params:[i]},{dedupe:!0}):t?c=await e.request({method:"eth_getTransactionByBlockHashAndIndex",params:[t,K(s)]},{dedupe:!0}):c=await e.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[a||o,K(s)]},{dedupe:!!a}),!c)throw new Lp({blockHash:t,blockNumber:r,blockTag:o,hash:i,index:s});return(((y=(d=(u=e.chain)==null?void 0:u.formatters)==null?void 0:d.transaction)==null?void 0:y.format)||fo)(c)}async function u2(e,{hash:t,transactionReceipt:r}){const[n,i]=await Promise.all([ee(e,as,"getBlockNumber")({}),t?ee(e,Yu,"getTransaction")({hash:t}):void 0]),s=(r==null?void 0:r.blockNumber)||(i==null?void 0:i.blockNumber);return s?n-s+1n:0n}async function jc(e,{hash:t}){var i,s,o;const r=await e.request({method:"eth_getTransactionReceipt",params:[t]},{dedupe:!0});if(!r)throw new Mp({hash:t});return(((o=(s=(i=e.chain)==null?void 0:i.formatters)==null?void 0:s.transactionReceipt)==null?void 0:o.format)||Oh)(r)}async function f2(e,t){var A;const{account:r,allowFailure:n=!0,batchSize:i,blockNumber:s,blockTag:o,multicallAddress:a,stateOverride:c}=t,f=t.contracts,u=i??(typeof((A=e.batch)==null?void 0:A.multicall)=="object"&&e.batch.multicall.batchSize||1024);let d=a;if(!d){if(!e.chain)throw new Error("client chain not configured. multicallAddress is required.");d=Xn({blockNumber:s,chain:e.chain,contract:"multicall3"})}const y=[[]];let p=0,g=0;for(let P=0;P<f.length;P++){const{abi:w,address:_,args:T,functionName:I}=f[P];try{const R=At({abi:w,args:T,functionName:I});g+=(R.length-2)/2,u>0&&g>u&&y[p].length>0&&(p++,g=(R.length-2)/2,y[p]=[]),y[p]=[...y[p],{allowFailure:!0,callData:R,target:_}]}catch(R){const L=Jr(R,{abi:w,address:_,args:T,docsPath:"/docs/contract/multicall",functionName:I,sender:r});if(!n)throw L;y[p]=[...y[p],{allowFailure:!0,callData:"0x",target:_}]}}const b=await Promise.allSettled(y.map(P=>ee(e,Wt,"readContract")({abi:$c,account:r,address:d,args:[P],blockNumber:s,blockTag:o,functionName:"aggregate3",stateOverride:c}))),E=[];for(let P=0;P<b.length;P++){const w=b[P];if(w.status==="rejected"){if(!n)throw w.reason;for(let T=0;T<y[P].length;T++)E.push({status:"failure",error:w.reason,result:void 0});continue}const _=w.value;for(let T=0;T<_.length;T++){const{returnData:I,success:R}=_[T],{callData:L}=y[P][T],{abi:S,address:$,functionName:C,args:U}=f[E.length];try{if(L==="0x")throw new Ji;if(!R)throw new oo({data:I});const j=an({abi:S,args:U,data:I,functionName:C});E.push(n?{result:j,status:"success"}:j)}catch(j){const V=Jr(j,{abi:S,address:$,args:U,docsPath:"/docs/contract/multicall",functionName:C});if(!n)throw V;E.push({error:V,result:void 0,status:"failure"})}}}if(E.length!==f.length)throw new D("multicall results mismatch");return E}async function zc(e,t){const{blockNumber:r,blockTag:n="latest",blocks:i,returnFullTransactions:s,traceTransfers:o,validation:a}=t;try{const c=[];for(const y of i){const p=y.blockOverrides?bh(y.blockOverrides):void 0,g=y.calls.map(E=>{const A=E,P=A.account?ke(A.account):void 0,w=A.abi?At(A):A.data,_={...A,data:A.dataSuffix?ut([w||"0x",A.dataSuffix]):w,from:A.from??(P==null?void 0:P.address)};return on(_),Yn(_)}),b=y.stateOverrides?Au(y.stateOverrides):void 0;c.push({blockOverrides:p,calls:g,stateOverrides:b})}const u=(typeof r=="bigint"?K(r):void 0)||n;return(await e.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:s,traceTransfers:o,validation:a},u]})).map((y,p)=>({...Su(y),calls:y.calls.map((g,b)=>{var $,C;const{abi:E,args:A,functionName:P,to:w}=i[p].calls[b],_=(($=g.error)==null?void 0:$.data)??g.returnData,T=BigInt(g.gasUsed),I=(C=g.logs)==null?void 0:C.map(U=>cr(U)),R=g.status==="0x1"?"success":"failure",L=E&&R==="success"&&_!=="0x"?an({abi:E,data:_,functionName:P}):null,S=(()=>{var j;if(R==="success")return;let U;if(((j=g.error)==null?void 0:j.data)==="0x"?U=new Ji:g.error&&(U=new oo(g.error)),!!U)return Jr(U,{abi:E??[],address:w??"0x",args:A,functionName:P??"<unknown>"})})();return{data:_,gasUsed:T,logs:I,status:R,...R==="success"?{result:L}:{error:S}}})}))}catch(c){const f=c,u=ao(f,{});throw u instanceof is?f:u}}function a0(e,t={}){const{as:r=typeof e=="string"?"Hex":"Bytes"}=t,n=Sp(aw(e));return r==="Bytes"?n:yh(n)}class d2 extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){const r=super.get(t);return super.has(t)&&r!==void 0&&(this.delete(t),super.set(t,r)),r}set(t,r){if(super.set(t,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const l2={checksum:new d2(8192)},Jo=l2.checksum,p2=/^0x[a-fA-F0-9]{40}$/;function Ao(e,t={}){const{strict:r=!0}=t;if(!p2.test(e))throw new ud({address:e,cause:new y2});if(r){if(e.toLowerCase()===e)return;if(h2(e)!==e)throw new ud({address:e,cause:new m2})}}function h2(e){if(Jo.has(e))return Jo.get(e);Ao(e,{strict:!1});const t=e.substring(2).toLowerCase(),r=a0(fw(t),{as:"Bytes"}),n=t.split("");for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&n[s]&&(n[s]=n[s].toUpperCase()),(r[s>>1]&15)>=8&&n[s+1]&&(n[s+1]=n[s+1].toUpperCase());const i=`0x${n.join("")}`;return Jo.set(e,i),i}function qc(e,t={}){const{strict:r=!0}=t??{};try{return Ao(e,{strict:r}),!0}catch{return!1}}class ud extends xe{constructor({address:t,cause:r}){super(`Address "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class y2 extends xe{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 m2 extends xe{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}function Gc(e){let t=!0,r="",n=0,i="",s=!1;for(let o=0;o<e.length;o++){const a=e[o];if(["(",")",","].includes(a)&&(t=!0),a==="("&&n++,a===")"&&n--,!!t){if(n===0){if(a===" "&&["event","function","error",""].includes(i))i="";else if(i+=a,a===")"){s=!0;break}continue}if(a===" "){e[o-1]!==","&&r!==","&&r!==",("&&(r="",t=!1);continue}i+=a,r+=a}}if(!s)throw new xe("Unable to normalize signature.");return i}function Vc(e,t){const r=typeof e,n=t.type;switch(n){case"address":return qc(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in t?Object.values(t.components).every((i,s)=>Vc(Object.values(e)[s],i)):/^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"||e instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(e)&&e.every(i=>Vc(i,{...t,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function c0(e,t,r){for(const n in e){const i=e[n],s=t[n];if(i.type==="tuple"&&s.type==="tuple"&&"components"in i&&"components"in s)return c0(i.components,s.components,r[n]);const o=[i.type,s.type];if(o.includes("address")&&o.includes("bytes20")?!0:o.includes("address")&&o.includes("string")?qc(r[n],{strict:!1}):o.includes("address")&&o.includes("bytes")?qc(r[n],{strict:!1}):!1)return o}}function u0(e,t={}){const{prepare:r=!0}=t,n=Array.isArray(e)||typeof e=="string"?_f(e):e;return{...n,...r?{hash:_n(n)}:{}}}function g2(e,t,r){const{args:n=[],prepare:i=!0}=r??{},s=gw(t,{strict:!1}),o=e.filter(f=>s?f.type==="function"||f.type==="error"?f0(f)===ju(t,0,4):f.type==="event"?_n(f)===t:!1:"name"in f&&f.name===t);if(o.length===0)throw new Wc({name:t});if(o.length===1)return{...o[0],...i?{hash:_n(o[0])}:{}};let a;for(const f of o){if(!("inputs"in f))continue;if(!n||n.length===0){if(!f.inputs||f.inputs.length===0)return{...f,...i?{hash:_n(f)}:{}};continue}if(!f.inputs||f.inputs.length===0||f.inputs.length!==n.length)continue;if(n.every((d,y)=>{const p="inputs"in f&&f.inputs[y];return p?Vc(d,p):!1})){if(a&&"inputs"in a&&a.inputs){const d=c0(f.inputs,a.inputs,n);if(d)throw new w2({abiItem:f,type:d[0]},{abiItem:a,type:d[1]})}a=f}}const c=(()=>{if(a)return a;const[f,...u]=o;return{...f,overloads:u}})();if(!c)throw new Wc({name:t});return{...c,...i?{hash:_n(c)}:{}}}function f0(e){return ju(_n(e),0,4)}function b2(e){const t=typeof e=="string"?e:Gs(e);return Gc(t)}function _n(e){return typeof e!="string"&&"hash"in e&&e.hash?e.hash:a0(Du(b2(e)))}class w2 extends xe{constructor(t,r){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${t.type}\` in \`${Gc(Gs(t.abiItem))}\`, and`,`\`${r.type}\` in \`${Gc(Gs(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 Wc extends xe{constructor({name:t,data:r,type:n="item"}){const i=t?` with name "${t}"`:r?` with data "${r}"`:"";super(`ABI ${n}${i} not found.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}const v2=/^(.*)\[([0-9]*)\]$/,E2=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,d0=/^(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 x2({checksumAddress:e,parameters:t,values:r}){const n=[];for(let i=0;i<t.length;i++)n.push(Zu({checksumAddress:e,parameter:t[i],value:r[i]}));return n}function Zu({checksumAddress:e=!1,parameter:t,value:r}){const n=t,i=B2(n.type);if(i){const[s,o]=i;return _2(r,{checksumAddress:e,length:s,parameter:{...n,type:o}})}if(n.type==="tuple")return k2(r,{checksumAddress:e,parameter:n});if(n.type==="address")return A2(r,{checksum:e});if(n.type==="bool")return P2(r);if(n.type.startsWith("uint")||n.type.startsWith("int")){const s=n.type.startsWith("int"),[,,o="256"]=d0.exec(n.type)??[];return T2(r,{signed:s,size:Number(o)})}if(n.type.startsWith("bytes"))return S2(r,{type:n.type});if(n.type==="string")return I2(r);throw new y0(n.type)}function Xu(e){let t=0;for(let s=0;s<e.length;s++){const{dynamic:o,encoded:a}=e[s];o?t+=32:t+=xt(a)}const r=[],n=[];let i=0;for(let s=0;s<e.length;s++){const{dynamic:o,encoded:a}=e[s];o?(r.push(Je(t+i,{size:32})),n.push(a),i+=xt(a)):r.push(a)}return Vt(...r,...n)}function A2(e,t){const{checksum:r=!1}=t;return Ao(e,{strict:r}),{dynamic:!1,encoded:en(e.toLowerCase())}}function _2(e,t){const{checksumAddress:r,length:n,parameter:i}=t,s=n===null;if(!Array.isArray(e))throw new C2(e);if(!s&&e.length!==n)throw new O2({expectedLength:n,givenLength:e.length,type:`${i.type}[${n}]`});let o=!1;const a=[];for(let c=0;c<e.length;c++){const f=Zu({checksumAddress:r,parameter:i,value:e[c]});f.dynamic&&(o=!0),a.push(f)}if(s||o){const c=Xu(a);if(s){const f=Je(a.length,{size:32});return{dynamic:!0,encoded:a.length>0?Vt(f,c):f}}if(o)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:Vt(...a.map(({encoded:c})=>c))}}function S2(e,{type:t}){const[,r]=t.split("bytes"),n=xt(e);if(!r){let i=e;return n%32!==0&&(i=tn(i,Math.ceil((e.length-2)/2/32)*32)),{dynamic:!0,encoded:Vt(en(Je(n,{size:32})),i)}}if(n!==Number.parseInt(r))throw new p0({expectedSize:Number.parseInt(r),value:e});return{dynamic:!1,encoded:tn(e)}}function P2(e){if(typeof e!="boolean")throw new xe(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:en(hh(e))}}function T2(e,{signed:t,size:r}){if(typeof r=="number"){const n=2n**(BigInt(r)-(t?1n:0n))-1n,i=t?-n-1n:0n;if(e>n||e<i)throw new mh({max:n.toString(),min:i.toString(),signed:t,size:r/8,value:e.toString()})}return{dynamic:!1,encoded:Je(e,{size:32,signed:t})}}function I2(e){const t=Du(e),r=Math.ceil(xt(t)/32),n=[];for(let i=0;i<r;i++)n.push(tn(ju(t,i*32,(i+1)*32)));return{dynamic:!0,encoded:Vt(tn(Je(xt(t),{size:32})),...n)}}function k2(e,t){const{checksumAddress:r,parameter:n}=t;let i=!1;const s=[];for(let o=0;o<n.components.length;o++){const a=n.components[o],c=Array.isArray(e)?o:a.name,f=Zu({checksumAddress:r,parameter:a,value:e[c]});s.push(f),f.dynamic&&(i=!0)}return{dynamic:i,encoded:i?Xu(s):Vt(...s.map(({encoded:o})=>o))}}function B2(e){const t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function l0(e,t,r){const{checksumAddress:n=!1}={};if(e.length!==t.length)throw new h0({expectedLength:e.length,givenLength:t.length});const i=x2({checksumAddress:n,parameters:e,values:t}),s=Xu(i);return s.length===0?"0x":s}function Kc(e,t){if(e.length!==t.length)throw new h0({expectedLength:e.length,givenLength:t.length});const r=[];for(let n=0;n<e.length;n++){const i=e[n],s=t[n];r.push(Kc.encode(i,s))}return Vt(...r)}(function(e){function t(r,n,i=!1){if(r==="address"){const c=n;return Ao(c),en(c.toLowerCase(),i?32:0)}if(r==="string")return Du(n);if(r==="bytes")return n;if(r==="bool")return en(hh(n),i?32:1);const s=r.match(d0);if(s){const[c,f,u="256"]=s,d=Number.parseInt(u)/8;return Je(n,{size:i?32:d,signed:f==="int"})}const o=r.match(E2);if(o){const[c,f]=o;if(Number.parseInt(f)!==(n.length-2)/2)throw new p0({expectedSize:Number.parseInt(f),value:n});return tn(n,i?32:0)}const a=r.match(v2);if(a&&Array.isArray(n)){const[c,f]=a,u=[];for(let d=0;d<n.length;d++)u.push(t(f,n[d],!0));return u.length===0?"0x":Vt(...u)}throw new y0(r)}e.encode=t})(Kc||(Kc={}));class O2 extends xe{constructor({expectedLength:t,givenLength:r,type:n}){super(`Array length mismatch for type \`${n}\`. Expected: \`${t}\`. Given: \`${r}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"})}}class p0 extends xe{constructor({expectedSize:t,value:r}){super(`Size of bytes "${r}" (bytes${xt(r)}) does not match expected size (bytes${t}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class h0 extends xe{constructor({expectedLength:t,givenLength:r}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${t}`,`Given length (values): ${r}`].join(`
44
+ `)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class C2 extends xe{constructor(t){super(`Value \`${t}\` is not a valid array.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"})}}class y0 extends xe{constructor(t){super(`Type \`${t}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}function R2(e,t){var i;const{bytecode:r,args:n}=t;return Vt(r,(i=e.inputs)!=null&&i.length&&(n!=null&&n.length)?l0(e.inputs,n):"0x")}function N2(e){return u0(e)}function F2(e,...t){const{overloads:r}=e,n=r?$2([e,...r],e.name,{args:t[0]}):e,i=U2(n),s=t.length>0?l0(n.inputs,t[0]):void 0;return s?Vt(i,s):i}function hn(e,t={}){return u0(e,t)}function $2(e,t,r){const n=g2(e,t,r);if(n.type!=="function")throw new Wc({name:t,type:"function"});return n}function U2(e){return f0(e)}const H2="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",$t="0x0000000000000000000000000000000000000000",L2="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033";async function M2(e,t){const{blockNumber:r,blockTag:n,calls:i,stateOverrides:s,traceAssetChanges:o,traceTransfers:a,validation:c}=t,f=t.account?ke(t.account):void 0;if(o&&!f)throw new D("`account` is required when `traceAssetChanges` is true");const u=f?R2(N2("constructor(bytes, bytes)"),{bytecode:Eh,args:[L2,F2(hn("function getBalance(address)"),[f.address])]}):void 0,d=o?await Promise.all(t.calls.map(async M=>{if(!M.data&&!M.abi)return;const{accessList:B}=await qh(e,{account:f.address,...M,data:M.abi?At(M):M.data});return B.map(({address:q,storageKeys:W})=>W.length>0?q:null)})).then(M=>M.flat().filter(Boolean)):[],y=await zc(e,{blockNumber:r,blockTag:n,blocks:[...o?[{calls:[{data:u}],stateOverrides:s},{calls:d.map((M,B)=>({abi:[hn("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[f.address],to:M,from:$t,nonce:B})),stateOverrides:[{address:$t,nonce:0}]}]:[],{calls:[...i,{}].map(M=>({...M,from:f==null?void 0:f.address})),stateOverrides:s},...o?[{calls:[{data:u}]},{calls:d.map((M,B)=>({abi:[hn("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[f.address],to:M,from:$t,nonce:B})),stateOverrides:[{address:$t,nonce:0}]},{calls:d.map((M,B)=>({to:M,abi:[hn("function decimals() returns (uint256)")],functionName:"decimals",from:$t,nonce:B})),stateOverrides:[{address:$t,nonce:0}]},{calls:d.map((M,B)=>({to:M,abi:[hn("function tokenURI(uint256) returns (string)")],functionName:"tokenURI",args:[0n],from:$t,nonce:B})),stateOverrides:[{address:$t,nonce:0}]},{calls:d.map((M,B)=>({to:M,abi:[hn("function symbol() returns (string)")],functionName:"symbol",from:$t,nonce:B})),stateOverrides:[{address:$t,nonce:0}]}]:[]],traceTransfers:a,validation:c}),p=o?y[2]:y[0],[g,b,,E,A,P,w,_]=o?y:[],{calls:T,...I}=p,R=T.slice(0,-1)??[],L=(g==null?void 0:g.calls)??[],S=(b==null?void 0:b.calls)??[],$=[...L,...S].map(M=>M.status==="success"?Ue(M.data):null),C=(E==null?void 0:E.calls)??[],U=(A==null?void 0:A.calls)??[],j=[...C,...U].map(M=>M.status==="success"?Ue(M.data):null),V=((P==null?void 0:P.calls)??[]).map(M=>M.status==="success"?M.result:null),Y=((_==null?void 0:_.calls)??[]).map(M=>M.status==="success"?M.result:null),X=((w==null?void 0:w.calls)??[]).map(M=>M.status==="success"?M.result:null),J=[];for(const[M,B]of j.entries()){const q=$[M];if(typeof B!="bigint"||typeof q!="bigint")continue;const W=V[M-1],k=Y[M-1],N=X[M-1],H=M===0?{address:H2,decimals:18,symbol:"ETH"}:{address:d[M-1],decimals:N||W?Number(W??1):void 0,symbol:k??void 0};J.some(Z=>Z.token.address===H.address)||J.push({token:H,value:{pre:q,post:B,diff:B-q}})}return{assetChanges:J,block:I,results:R}}class m0 extends pu{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,sg(t);const n=eo(r);if(this.iHash=t.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 i=this.blockLen,s=new Uint8Array(i);s.set(n.length>i?t.create().update(n).digest():n);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=t.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),Or(s)}update(t){return Nn(this),this.iHash.update(t),this}digestInto(t){Nn(this),Bt(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:n,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return t=t,t.finished=i,t.destroyed=s,t.blockLen=o,t.outputLen=a,t.oHash=r._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const g0=(e,t,r)=>new m0(e,t).update(r).digest();g0.create=(e,t)=>new m0(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const nt=BigInt(0),et=BigInt(1),Mr=BigInt(2),D2=BigInt(3),b0=BigInt(4),w0=BigInt(5),v0=BigInt(8);function bt(e,t){const r=e%t;return r>=nt?r:t+r}function ht(e,t,r){let n=e;for(;t-- >nt;)n*=n,n%=r;return n}function fd(e,t){if(e===nt)throw new Error("invert: expected non-zero number");if(t<=nt)throw new Error("invert: expected positive modulus, got "+t);let r=bt(e,t),n=t,i=nt,s=et;for(;r!==nt;){const a=n/r,c=n%r,f=i-s*a;n=r,r=c,i=s,s=f}if(n!==et)throw new Error("invert: does not exist");return bt(i,t)}function E0(e,t){const r=(e.ORDER+et)/b0,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw new Error("Cannot find square root");return n}function j2(e,t){const r=(e.ORDER-w0)/v0,n=e.mul(t,Mr),i=e.pow(n,r),s=e.mul(t,i),o=e.mul(e.mul(s,Mr),i),a=e.mul(s,e.sub(o,e.ONE));if(!e.eql(e.sqr(a),t))throw new Error("Cannot find square root");return a}function z2(e){if(e<BigInt(3))throw new Error("sqrt is not defined for small field");let t=e-et,r=0;for(;t%Mr===nt;)t/=Mr,r++;let n=Mr;const i=_o(e);for(;dd(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return E0;let s=i.pow(n,t);const o=(t+et)/Mr;return function(c,f){if(c.is0(f))return f;if(dd(c,f)!==1)throw new Error("Cannot find square root");let u=r,d=c.mul(c.ONE,s),y=c.pow(f,t),p=c.pow(f,o);for(;!c.eql(y,c.ONE);){if(c.is0(y))return c.ZERO;let g=1,b=c.sqr(y);for(;!c.eql(b,c.ONE);)if(g++,b=c.sqr(b),g===u)throw new Error("Cannot find square root");const E=et<<BigInt(u-g-1),A=c.pow(d,E);u=g,d=c.sqr(A),y=c.mul(y,d),p=c.mul(p,A)}return p}}function q2(e){return e%b0===D2?E0:e%v0===w0?j2:z2(e)}const G2=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function V2(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=G2.reduce((n,i)=>(n[i]="function",n),t);return Lu(e,r),e}function W2(e,t,r){if(r<nt)throw new Error("invalid exponent, negatives unsupported");if(r===nt)return e.ONE;if(r===et)return t;let n=e.ONE,i=t;for(;r>nt;)r&et&&(n=e.mul(n,i)),i=e.sqr(i),r>>=et;return n}function x0(e,t,r=!1){const n=new Array(t.length).fill(r?e.ZERO:void 0),i=t.reduce((o,a,c)=>e.is0(a)?o:(n[c]=o,e.mul(o,a)),e.ONE),s=e.inv(i);return t.reduceRight((o,a,c)=>e.is0(a)?o:(n[c]=e.mul(o,n[c]),e.mul(o,a)),s),n}function dd(e,t){const r=(e.ORDER-et)/Mr,n=e.pow(t,r),i=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),o=e.eql(n,e.neg(e.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function K2(e,t){t!==void 0&&Si(t);const r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function _o(e,t,r=!1,n={}){if(e<=nt)throw new Error("invalid field: expected ORDER > 0, got "+e);let i,s;if(typeof t=="object"&&t!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");const u=t;u.BITS&&(i=u.BITS),u.sqrt&&(s=u.sqrt),typeof u.isLE=="boolean"&&(r=u.isLE)}else typeof t=="number"&&(i=t),n.sqrt&&(s=n.sqrt);const{nBitLength:o,nByteLength:a}=K2(e,i);if(a>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let c;const f=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:a,MASK:ho(o),ZERO:nt,ONE:et,create:u=>bt(u,e),isValid:u=>{if(typeof u!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof u);return nt<=u&&u<e},is0:u=>u===nt,isValidNot0:u=>!f.is0(u)&&f.isValid(u),isOdd:u=>(u&et)===et,neg:u=>bt(-u,e),eql:(u,d)=>u===d,sqr:u=>bt(u*u,e),add:(u,d)=>bt(u+d,e),sub:(u,d)=>bt(u-d,e),mul:(u,d)=>bt(u*d,e),pow:(u,d)=>W2(f,u,d),div:(u,d)=>bt(u*fd(d,e),e),sqrN:u=>u*u,addN:(u,d)=>u+d,subN:(u,d)=>u-d,mulN:(u,d)=>u*d,inv:u=>fd(u,e),sqrt:s||(u=>(c||(c=q2(e)),c(f,u))),toBytes:u=>r?dh(u,a):Hu(u,a),fromBytes:u=>{if(u.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+u.length);return r?fh(u):po(u)},invertBatch:u=>x0(f,u),cmov:(u,d,y)=>y?d:u});return Object.freeze(f)}function A0(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function _0(e){const t=A0(e);return t+Math.ceil(t/2)}function Y2(e,t,r=!1){const n=e.length,i=A0(t),s=_0(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const o=r?fh(e):po(e),a=bt(o,t-et)+et;return r?dh(a,i):Hu(a,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Hn=BigInt(0),Dr=BigInt(1);function mi(e,t){const r=t.negate();return e?r:t}function Z2(e,t,r){const n=o=>o.pz,i=x0(e.Fp,r.map(n));return r.map((o,a)=>o.toAffine(i[a])).map(e.fromAffine)}function S0(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Qo(e,t){S0(e,t);const r=Math.ceil(t/e)+1,n=2**(e-1),i=2**e,s=ho(e),o=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:i,shiftBy:o}}function ld(e,t,r){const{windowSize:n,mask:i,maxNumber:s,shiftBy:o}=r;let a=Number(e&i),c=e>>o;a>n&&(a-=s,c+=Dr);const f=t*n,u=f+Math.abs(a)-1,d=a===0,y=a<0,p=t%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:y,isNegF:p,offsetF:f}}function X2(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function J2(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}const ea=new WeakMap,P0=new WeakMap;function ta(e){return P0.get(e)||1}function pd(e){if(e!==Hn)throw new Error("invalid wNAF")}function Q2(e,t){return{constTimeNegate:mi,hasPrecomputes(r){return ta(r)!==1},unsafeLadder(r,n,i=e.ZERO){let s=r;for(;n>Hn;)n&Dr&&(i=i.add(s)),s=s.double(),n>>=Dr;return i},precomputeWindow(r,n){const{windows:i,windowSize:s}=Qo(n,t),o=[];let a=r,c=a;for(let f=0;f<i;f++){c=a,o.push(c);for(let u=1;u<s;u++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,n,i){let s=e.ZERO,o=e.BASE;const a=Qo(r,t);for(let c=0;c<a.windows;c++){const{nextN:f,offset:u,isZero:d,isNeg:y,isNegF:p,offsetF:g}=ld(i,c,a);i=f,d?o=o.add(mi(p,n[g])):s=s.add(mi(y,n[u]))}return pd(i),{p:s,f:o}},wNAFUnsafe(r,n,i,s=e.ZERO){const o=Qo(r,t);for(let a=0;a<o.windows&&i!==Hn;a++){const{nextN:c,offset:f,isZero:u,isNeg:d}=ld(i,a,o);if(i=c,!u){const y=n[f];s=s.add(d?y.negate():y)}}return pd(i),s},getPrecomputes(r,n,i){let s=ea.get(n);return s||(s=this.precomputeWindow(n,r),r!==1&&(typeof i=="function"&&(s=i(s)),ea.set(n,s))),s},wNAFCached(r,n,i){const s=ta(r);return this.wNAF(s,this.getPrecomputes(s,r,i),n)},wNAFCachedUnsafe(r,n,i,s){const o=ta(r);return o===1?this.unsafeLadder(r,n,s):this.wNAFUnsafe(o,this.getPrecomputes(o,r,i),n,s)},setWindowSize(r,n){S0(n,t),P0.set(r,n),ea.delete(r)}}}function ev(e,t,r,n){let i=t,s=e.ZERO,o=e.ZERO;for(;r>Hn||n>Hn;)r&Dr&&(s=s.add(i)),n&Dr&&(o=o.add(i)),i=i.double(),r>>=Dr,n>>=Dr;return{p1:s,p2:o}}function tv(e,t,r,n){X2(r,e),J2(n,t);const i=r.length,s=n.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=Zb(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const f=ho(c),u=new Array(Number(f)+1).fill(o),d=Math.floor((t.BITS-1)/c)*c;let y=o;for(let p=d;p>=0;p-=c){u.fill(o);for(let b=0;b<s;b++){const E=n[b],A=Number(E>>BigInt(p)&f);u[A]=u[A].add(r[b])}let g=o;for(let b=u.length-1,E=o;b>0;b--)E=E.add(u[b]),g=g.add(E);if(y=y.add(g),p!==0)for(let b=0;b<c;b++)y=y.double()}return y}function hd(e,t){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return V2(t),t}else return _o(e)}function rv(e,t,r={}){if(!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(const a of["p","n","h"]){const c=t[a];if(!(typeof c=="bigint"&&c>Hn))throw new Error(`CURVE.${a} must be positive bigint`)}const n=hd(t.p,r.Fp),i=hd(t.n,r.Fn),o=["Gx","Gy","a","b"];for(const a of o)if(!n.isValid(t[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return{Fp:n,Fn:i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function yd(e){e.lowS!==void 0&&Ws("lowS",e.lowS),e.prehash!==void 0&&Ws("prehash",e.prehash)}class nv extends Error{constructor(t=""){super(t)}}const nr={Err:nv,_tlv:{encode:(e,t)=>{const{Err:r}=nr;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");const n=t.length/2,i=gs(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?gs(i.length/2|128):"";return gs(e)+s+i+t},decode(e,t){const{Err:r}=nr;let n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");const i=t[n++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&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 f=t.subarray(n,n+c);if(f.length!==c)throw new r("tlv.decode: length bytes not complete");if(f[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const u of f)o=o<<8|u;if(n+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=t.subarray(n,n+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+o)}}},_int:{encode(e){const{Err:t}=nr;if(e<gi)throw new t("integer: negative integers are not allowed");let r=gs(e);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){const{Err:t}=nr;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return po(e)}},toSig(e){const{Err:t,_int:r,_tlv:n}=nr,i=mt("signature",e),{v:s,l:o}=n.decode(48,i);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,s),{v:f,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(f)}},hexFromSig(e){const{_tlv:t,_int:r}=nr,n=t.encode(2,r.encode(e.r)),i=t.encode(2,r.encode(e.s)),s=n+i;return t.encode(48,s)}},gi=BigInt(0),bi=BigInt(1),iv=BigInt(2),As=BigInt(3),sv=BigInt(4);function ov(e,t,r){function n(i){const s=e.sqr(i),o=e.mul(s,i);return e.add(e.add(o,e.mul(i,t)),r)}return n}function T0(e,t,r){const{BYTES:n}=e;function i(s){let o;if(typeof s=="bigint")o=s;else{let a=mt("private key",s);if(t){if(!t.includes(a.length*2))throw new Error("invalid private key");const c=new Uint8Array(n);c.set(a,c.length-a.length),a=c}try{o=e.fromBytes(a)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof s}`)}}if(r&&(o=e.create(o)),!e.isValidNot0(o))throw new Error("invalid private key: out of range [1..N-1]");return o}return i}function av(e,t={}){const{Fp:r,Fn:n}=rv("weierstrass",e,t),{h:i,n:s}=e;Lu(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:o}=t;if(o&&(!r.is0(e.a)||typeof o.beta!="bigint"||typeof o.splitScalar!="function"))throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');function a(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function c(L,S,$){const{x:C,y:U}=S.toAffine(),j=r.toBytes(C);if(Ws("isCompressed",$),$){a();const V=!r.isOdd(U);return Hr(I0(V),j)}else return Hr(Uint8Array.of(4),j,r.toBytes(U))}function f(L){Bt(L);const S=r.BYTES,$=S+1,C=2*S+1,U=L.length,j=L[0],V=L.subarray(1);if(U===$&&(j===2||j===3)){const Y=r.fromBytes(V);if(!r.isValid(Y))throw new Error("bad point: is not on curve, wrong x");const X=y(Y);let J;try{J=r.sqrt(X)}catch(q){const W=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+W)}a();const M=r.isOdd(J);return(j&1)===1!==M&&(J=r.neg(J)),{x:Y,y:J}}else if(U===C&&j===4){const Y=r.fromBytes(V.subarray(S*0,S*1)),X=r.fromBytes(V.subarray(S*1,S*2));if(!p(Y,X))throw new Error("bad point: is not on curve");return{x:Y,y:X}}else throw new Error(`bad point: got length ${U}, expected compressed=${$} or uncompressed=${C}`)}const u=t.toBytes||c,d=t.fromBytes||f,y=ov(r,e.a,e.b);function p(L,S){const $=r.sqr(S),C=y(L);return r.eql($,C)}if(!p(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const g=r.mul(r.pow(e.a,As),sv),b=r.mul(r.sqr(e.b),BigInt(27));if(r.is0(r.add(g,b)))throw new Error("bad curve params: a or b");function E(L,S,$=!1){if(!r.isValid(S)||$&&r.is0(S))throw new Error(`bad point coordinate ${L}`);return S}function A(L){if(!(L instanceof T))throw new Error("ProjectivePoint expected")}const P=Kf((L,S)=>{const{px:$,py:C,pz:U}=L;if(r.eql(U,r.ONE))return{x:$,y:C};const j=L.is0();S==null&&(S=j?r.ONE:r.inv(U));const V=r.mul($,S),Y=r.mul(C,S),X=r.mul(U,S);if(j)return{x:r.ZERO,y:r.ZERO};if(!r.eql(X,r.ONE))throw new Error("invZ was invalid");return{x:V,y:Y}}),w=Kf(L=>{if(L.is0()){if(t.allowInfinityPoint&&!r.is0(L.py))return;throw new Error("bad point: ZERO")}const{x:S,y:$}=L.toAffine();if(!r.isValid(S)||!r.isValid($))throw new Error("bad point: x or y not field elements");if(!p(S,$))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function _(L,S,$,C,U){return $=new T(r.mul($.px,L),$.py,$.pz),S=mi(C,S),$=mi(U,$),S.add($)}class T{constructor(S,$,C){this.px=E("x",S),this.py=E("y",$,!0),this.pz=E("z",C),Object.freeze(this)}static fromAffine(S){const{x:$,y:C}=S||{};if(!S||!r.isValid($)||!r.isValid(C))throw new Error("invalid affine point");if(S instanceof T)throw new Error("projective point not allowed");return r.is0($)&&r.is0(C)?T.ZERO:new T($,C,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(S){return Z2(T,"pz",S)}static fromBytes(S){return Bt(S),T.fromHex(S)}static fromHex(S){const $=T.fromAffine(d(mt("pointHex",S)));return $.assertValidity(),$}static fromPrivateKey(S){const $=T0(n,t.allowedPrivateKeyLengths,t.wrapPrivateKey);return T.BASE.multiply($(S))}static msm(S,$){return tv(T,n,S,$)}precompute(S=8,$=!0){return R.setWindowSize(this,S),$||this.multiply(As),this}_setWindowSize(S){this.precompute(S)}assertValidity(){w(this)}hasEvenY(){const{y:S}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(S)}equals(S){A(S);const{px:$,py:C,pz:U}=this,{px:j,py:V,pz:Y}=S,X=r.eql(r.mul($,Y),r.mul(j,U)),J=r.eql(r.mul(C,Y),r.mul(V,U));return X&&J}negate(){return new T(this.px,r.neg(this.py),this.pz)}double(){const{a:S,b:$}=e,C=r.mul($,As),{px:U,py:j,pz:V}=this;let Y=r.ZERO,X=r.ZERO,J=r.ZERO,M=r.mul(U,U),B=r.mul(j,j),q=r.mul(V,V),W=r.mul(U,j);return W=r.add(W,W),J=r.mul(U,V),J=r.add(J,J),Y=r.mul(S,J),X=r.mul(C,q),X=r.add(Y,X),Y=r.sub(B,X),X=r.add(B,X),X=r.mul(Y,X),Y=r.mul(W,Y),J=r.mul(C,J),q=r.mul(S,q),W=r.sub(M,q),W=r.mul(S,W),W=r.add(W,J),J=r.add(M,M),M=r.add(J,M),M=r.add(M,q),M=r.mul(M,W),X=r.add(X,M),q=r.mul(j,V),q=r.add(q,q),M=r.mul(q,W),Y=r.sub(Y,M),J=r.mul(q,B),J=r.add(J,J),J=r.add(J,J),new T(Y,X,J)}add(S){A(S);const{px:$,py:C,pz:U}=this,{px:j,py:V,pz:Y}=S;let X=r.ZERO,J=r.ZERO,M=r.ZERO;const B=e.a,q=r.mul(e.b,As);let W=r.mul($,j),k=r.mul(C,V),N=r.mul(U,Y),H=r.add($,C),Z=r.add(j,V);H=r.mul(H,Z),Z=r.add(W,k),H=r.sub(H,Z),Z=r.add($,U);let Q=r.add(j,Y);return Z=r.mul(Z,Q),Q=r.add(W,N),Z=r.sub(Z,Q),Q=r.add(C,U),X=r.add(V,Y),Q=r.mul(Q,X),X=r.add(k,N),Q=r.sub(Q,X),M=r.mul(B,Z),X=r.mul(q,N),M=r.add(X,M),X=r.sub(k,M),M=r.add(k,M),J=r.mul(X,M),k=r.add(W,W),k=r.add(k,W),N=r.mul(B,N),Z=r.mul(q,Z),k=r.add(k,N),N=r.sub(W,N),N=r.mul(B,N),Z=r.add(Z,N),W=r.mul(k,Z),J=r.add(J,W),W=r.mul(Q,Z),X=r.mul(H,X),X=r.sub(X,W),W=r.mul(H,k),M=r.mul(Q,M),M=r.add(M,W),new T(X,J,M)}subtract(S){return this.add(S.negate())}is0(){return this.equals(T.ZERO)}multiply(S){const{endo:$}=t;if(!n.isValidNot0(S))throw new Error("invalid scalar: out of range");let C,U;const j=V=>R.wNAFCached(this,V,T.normalizeZ);if($){const{k1neg:V,k1:Y,k2neg:X,k2:J}=$.splitScalar(S),{p:M,f:B}=j(Y),{p:q,f:W}=j(J);U=B.add(W),C=_($.beta,M,q,V,X)}else{const{p:V,f:Y}=j(S);C=V,U=Y}return T.normalizeZ([C,U])[0]}multiplyUnsafe(S){const{endo:$}=t,C=this;if(!n.isValid(S))throw new Error("invalid scalar: out of range");if(S===gi||C.is0())return T.ZERO;if(S===bi)return C;if(R.hasPrecomputes(this))return this.multiply(S);if($){const{k1neg:U,k1:j,k2neg:V,k2:Y}=$.splitScalar(S),{p1:X,p2:J}=ev(T,C,j,Y);return _($.beta,X,J,U,V)}else return R.wNAFCachedUnsafe(C,S)}multiplyAndAddUnsafe(S,$,C){const U=this.multiplyUnsafe($).add(S.multiplyUnsafe(C));return U.is0()?void 0:U}toAffine(S){return P(this,S)}isTorsionFree(){const{isTorsionFree:S}=t;return i===bi?!0:S?S(T,this):R.wNAFCachedUnsafe(this,s).is0()}clearCofactor(){const{clearCofactor:S}=t;return i===bi?this:S?S(T,this):this.multiplyUnsafe(i)}toBytes(S=!0){return Ws("isCompressed",S),this.assertValidity(),u(T,this,S)}toRawBytes(S=!0){return this.toBytes(S)}toHex(S=!0){return Pi(this.toBytes(S))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}T.BASE=new T(e.Gx,e.Gy,r.ONE),T.ZERO=new T(r.ZERO,r.ONE,r.ZERO),T.Fp=r,T.Fn=n;const I=n.BITS,R=Q2(T,t.endo?Math.ceil(I/2):I);return T}function I0(e){return Uint8Array.of(e?2:3)}function cv(e,t,r={}){Lu(t,{hash:"function"},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=t.randomBytes||lg,i=t.hmac||((C,...U)=>g0(t.hash,C,Hr(...U))),{Fp:s,Fn:o}=e,{ORDER:a,BITS:c}=o;function f(C){const U=a>>bi;return C>U}function u(C){return f(C)?o.neg(C):C}function d(C,U){if(!o.isValidNot0(U))throw new Error(`invalid signature ${C}: out of range 1..CURVE.n`)}class y{constructor(U,j,V){d("r",U),d("s",j),this.r=U,this.s=j,V!=null&&(this.recovery=V),Object.freeze(this)}static fromCompact(U){const j=o.BYTES,V=mt("compactSignature",U,j*2);return new y(o.fromBytes(V.subarray(0,j)),o.fromBytes(V.subarray(j,j*2)))}static fromDER(U){const{r:j,s:V}=nr.toSig(mt("DER",U));return new y(j,V)}assertValidity(){}addRecoveryBit(U){return new y(this.r,this.s,U)}recoverPublicKey(U){const j=s.ORDER,{r:V,s:Y,recovery:X}=this;if(X==null||![0,1,2,3].includes(X))throw new Error("recovery id invalid");if(a*iv<j&&X>1)throw new Error("recovery id is ambiguous for h>1 curve");const M=X===2||X===3?V+a:V;if(!s.isValid(M))throw new Error("recovery id 2 or 3 invalid");const B=s.toBytes(M),q=e.fromHex(Hr(I0((X&1)===0),B)),W=o.inv(M),k=w(mt("msgHash",U)),N=o.create(-k*W),H=o.create(Y*W),Z=e.BASE.multiplyUnsafe(N).add(q.multiplyUnsafe(H));if(Z.is0())throw new Error("point at infinify");return Z.assertValidity(),Z}hasHighS(){return f(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,o.neg(this.s),this.recovery):this}toBytes(U){if(U==="compact")return Hr(o.toBytes(this.r),o.toBytes(this.s));if(U==="der")return lu(nr.hexFromSig(this));throw new Error("invalid format")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Pi(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Pi(this.toBytes("compact"))}}const p=T0(o,r.allowedPrivateKeyLengths,r.wrapPrivateKey),g={isValidPrivateKey(C){try{return p(C),!0}catch{return!1}},normPrivateKeyToScalar:p,randomPrivateKey:()=>{const C=a;return Y2(n(_0(C)),C)},precompute(C=8,U=e.BASE){return U.precompute(C,!1)}};function b(C,U=!0){return e.fromPrivateKey(C).toBytes(U)}function E(C){if(typeof C=="bigint")return!1;if(C instanceof e)return!0;const j=mt("key",C).length,V=s.BYTES,Y=V+1,X=2*V+1;if(!(r.allowedPrivateKeyLengths||o.BYTES===Y))return j===Y||j===X}function A(C,U,j=!0){if(E(C)===!0)throw new Error("first arg must be private key");if(E(U)===!1)throw new Error("second arg must be public key");return e.fromHex(U).multiply(p(C)).toBytes(j)}const P=t.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");const U=po(C),j=C.length*8-c;return j>0?U>>BigInt(j):U},w=t.bits2int_modN||function(C){return o.create(P(C))},_=ho(c);function T(C){return Yb("num < 2^"+c,C,gi,_),o.toBytes(C)}function I(C,U,j=R){if(["recovered","canonical"].some(H=>H in j))throw new Error("sign() legacy options not supported");const{hash:V}=t;let{lowS:Y,prehash:X,extraEntropy:J}=j;Y==null&&(Y=!0),C=mt("msgHash",C),yd(j),X&&(C=mt("prehashed msgHash",V(C)));const M=w(C),B=p(U),q=[T(B),T(M)];if(J!=null&&J!==!1){const H=J===!0?n(s.BYTES):J;q.push(mt("extraEntropy",H))}const W=Hr(...q),k=M;function N(H){const Z=P(H);if(!o.isValidNot0(Z))return;const Q=o.inv(Z),ie=e.BASE.multiply(Z).toAffine(),ne=o.create(ie.x);if(ne===gi)return;const re=o.create(Q*o.create(k+ne*B));if(re===gi)return;let te=(ie.x===ne?0:2)|Number(ie.y&bi),se=re;return Y&&f(re)&&(se=u(re),te^=1),new y(ne,se,te)}return{seed:W,k2sig:N}}const R={lowS:t.lowS,prehash:!1},L={lowS:t.lowS,prehash:!1};function S(C,U,j=R){const{seed:V,k2sig:Y}=I(C,U,j);return Xb(t.hash.outputLen,o.BYTES,i)(V,Y)}e.BASE.precompute(8);function $(C,U,j,V=L){const Y=C;U=mt("msgHash",U),j=mt("publicKey",j),yd(V);const{lowS:X,prehash:J,format:M}=V;if("strict"in V)throw new Error("options.strict was renamed to lowS");if(M!==void 0&&!["compact","der","js"].includes(M))throw new Error('format must be "compact", "der" or "js"');const B=typeof Y=="string"||du(Y),q=!B&&!M&&typeof Y=="object"&&Y!==null&&typeof Y.r=="bigint"&&typeof Y.s=="bigint";if(!B&&!q)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let W,k;try{if(q)if(M===void 0||M==="js")W=new y(Y.r,Y.s);else throw new Error("invalid format");if(B){try{M!=="compact"&&(W=y.fromDER(Y))}catch(se){if(!(se instanceof nr.Err))throw se}!W&&M!=="der"&&(W=y.fromCompact(Y))}k=e.fromHex(j)}catch{return!1}if(!W||X&&W.hasHighS())return!1;J&&(U=t.hash(U));const{r:N,s:H}=W,Z=w(U),Q=o.inv(H),ie=o.create(Z*Q),ne=o.create(N*Q),re=e.BASE.multiplyUnsafe(ie).add(k.multiplyUnsafe(ne));return re.is0()?!1:o.create(re.x)===N}return Object.freeze({getPublicKey:b,getSharedSecret:A,sign:S,verify:$,utils:g,Point:e,Signature:y})}function uv(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=_o(t.n,e.nBitLength),i={Fp:r,Fn:n,allowedPrivateKeyLengths:e.allowedPrivateKeyLengths,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,wrapPrivateKey:e.wrapPrivateKey,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:i}}function fv(e){const{CURVE:t,curveOpts:r}=uv(e),n={hash:e.hash,hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:r,ecdsaOpts:n}}function dv(e,t){return Object.assign({},t,{ProjectivePoint:t.Point,CURVE:e})}function lv(e){const{CURVE:t,curveOpts:r,ecdsaOpts:n}=fv(e),i=av(t,r),s=cv(i,n,r);return dv(e,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function pv(e,t){const r=n=>lv({...e,hash:n});return{...r(t),create:r}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ks={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")};BigInt(0);const hv=BigInt(1),Yc=BigInt(2),md=(e,t)=>(e+t/Yc)/t;function yv(e){const t=Ks.p,r=BigInt(3),n=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),f=e*e*e%t,u=f*f*e%t,d=ht(u,r,t)*u%t,y=ht(d,r,t)*u%t,p=ht(y,Yc,t)*f%t,g=ht(p,i,t)*p%t,b=ht(g,s,t)*g%t,E=ht(b,a,t)*b%t,A=ht(E,c,t)*E%t,P=ht(A,a,t)*b%t,w=ht(P,r,t)*u%t,_=ht(w,o,t)*g%t,T=ht(_,n,t)*f%t,I=ht(T,Yc,t);if(!Zc.eql(Zc.sqr(I),e))throw new Error("Cannot find square root");return I}const Zc=_o(Ks.p,void 0,void 0,{sqrt:yv}),k0=pv({...Ks,Fp:Zc,lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=Ks.n,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-hv*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,o=BigInt("0x100000000000000000000000000000000"),a=md(s*e,t),c=md(-n*e,t);let f=bt(e-a*r-c*i,t),u=bt(-a*n-c*s,t);const d=f>o,y=u>o;if(d&&(f=t-f),y&&(u=t-u),f>o||u>o)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:d,k1:f,k2neg:y,k2:u}}}},Xp),mv=Object.freeze(Object.defineProperty({__proto__:null,secp256k1:k0},Symbol.toStringTag,{value:"Module"}));function gv({r:e,s:t,to:r="hex",v:n,yParity:i}){const s=(()=>{if(i===0||i===1)return i;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 k0.Signature(Ue(e),Ue(t)).toCompactHex()}${s===0?"1b":"1c"}`;return r==="hex"?o:kt(o)}async function Ju(e,t){var d,y,p;const{address:r,factory:n,factoryData:i,hash:s,signature:o,universalSignatureVerifierAddress:a=(p=(y=(d=e.chain)==null?void 0:d.contracts)==null?void 0:y.universalSignatureVerifier)==null?void 0:p.address,...c}=t,f=It(o)?o:typeof o=="object"&&"r"in o&&"s"in o?gv(o):Ce(o),u=await(async()=>!n&&!i||n2(f)?f:i2({address:n,data:i,signature:f}))();try{const g=a?{to:a,data:At({abi:td,functionName:"isValidSig",args:[r,s,u]}),...c}:{data:mo({abi:td,args:[r,s,u],bytecode:_w}),...c},{data:b}=await ee(e,os,"call")(g);return Wm(b??"0x0")}catch(g){try{if(ss(Tp(r),await jp({hash:s,signature:o})))return!0}catch{}if(g instanceof Dp)return!1;throw g}}async function bv(e,{address:t,message:r,factory:n,factoryData:i,signature:s,...o}){const a=s0(r);return Ju(e,{address:t,factory:n,factoryData:i,hash:a,signature:s,...o})}async function wv(e,t){const{address:r,factory:n,factoryData:i,signature:s,message:o,primaryType:a,types:c,domain:f,...u}=t,d=I1({message:o,primaryType:a,types:c,domain:f});return Ju(e,{address:r,factory:n,factoryData:i,hash:d,signature:s,...u})}function B0(e,{emitOnBegin:t=!1,emitMissed:r=!1,onBlockNumber:n,onError:i,poll:s,pollingInterval:o=e.pollingInterval}){const a=typeof s<"u"?s:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"));let c;return a?(()=>{const d=Oe(["watchBlockNumber",e.uid,t,r,o]);return ur(d,{onBlockNumber:n,onError:i},y=>Jn(async()=>{var p;try{const g=await ee(e,as,"getBlockNumber")({cacheTime:0});if(c){if(g===c)return;if(g-c>1&&r)for(let b=c+1n;b<g;b++)y.onBlockNumber(b,c),c=b}(!c||g>c)&&(y.onBlockNumber(g,c),c=g)}catch(g){(p=y.onError)==null||p.call(y,g)}},{emitOnBegin:t,interval:o}))})():(()=>{const d=Oe(["watchBlockNumber",e.uid,t,r]);return ur(d,{onBlockNumber:n,onError:i},y=>{let p=!0,g=()=>p=!1;return(async()=>{try{const b=(()=>{if(e.transport.type==="fallback"){const A=e.transport.transports.find(P=>P.config.type==="webSocket"||P.config.type==="ipc");return A?A.value:e.transport}return e.transport})(),{unsubscribe:E}=await b.subscribe({params:["newHeads"],onData(A){var w;if(!p)return;const P=Ue((w=A.result)==null?void 0:w.number);y.onBlockNumber(P,c),c=P},onError(A){var P;(P=y.onError)==null||P.call(y,A)}});g=E,p||g()}catch(b){i==null||i(b)}})(),()=>g()})})()}async function vv(e,{confirmations:t=1,hash:r,onReplaced:n,pollingInterval:i=e.pollingInterval,retryCount:s=6,retryDelay:o=({count:c})=>~~(1<<c)*200,timeout:a=18e4}){const c=Oe(["waitForTransactionReceipt",e.uid,r]);let f,u,d,y=!1,p,g;const{promise:b,resolve:E,reject:A}=zu(),P=a?setTimeout(()=>{g(),p(),A(new ab({hash:r}))},a):void 0;return p=ur(c,{onReplaced:n,resolve:E,reject:A},w=>{g=ee(e,B0,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:i,async onBlockNumber(_){const T=R=>{clearTimeout(P),g(),R(),p()};let I=_;if(!y)try{if(d){if(t>1&&(!d.blockNumber||I-d.blockNumber+1n<t))return;T(()=>w.resolve(d));return}if(f||(y=!0,await Dc(async()=>{f=await ee(e,Yu,"getTransaction")({hash:r}),f.blockNumber&&(I=f.blockNumber)},{delay:o,retryCount:s}),y=!1),d=await ee(e,jc,"getTransactionReceipt")({hash:r}),t>1&&(!d.blockNumber||I-d.blockNumber+1n<t))return;T(()=>w.resolve(d))}catch(R){if(R instanceof Lp||R instanceof Mp){if(!f){y=!1;return}try{u=f,y=!0;const L=await Dc(()=>ee(e,Gt,"getBlock")({blockNumber:I,includeTransactions:!0}),{delay:o,retryCount:s,shouldRetry:({error:C})=>C instanceof Vp});y=!1;const S=L.transactions.find(({from:C,nonce:U})=>C===u.from&&U===u.nonce);if(!S||(d=await ee(e,jc,"getTransactionReceipt")({hash:S.hash}),t>1&&(!d.blockNumber||I-d.blockNumber+1n<t)))return;let $="replaced";S.to===u.to&&S.value===u.value&&S.input===u.input?$="repriced":S.from===S.to&&S.value===0n&&($="cancelled"),T(()=>{var C;(C=w.onReplaced)==null||C.call(w,{reason:$,replacedTransaction:u,transaction:S,transactionReceipt:d}),w.resolve(d)})}catch(L){T(()=>w.reject(L))}}else T(()=>w.reject(R))}}})}),b}function Ev(e,{blockTag:t="latest",emitMissed:r=!1,emitOnBegin:n=!1,onBlock:i,onError:s,includeTransactions:o,poll:a,pollingInterval:c=e.pollingInterval}){const f=typeof a<"u"?a:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")),u=o??!1;let d;return f?(()=>{const g=Oe(["watchBlocks",e.uid,t,r,n,u,c]);return ur(g,{onBlock:i,onError:s},b=>Jn(async()=>{var E;try{const A=await ee(e,Gt,"getBlock")({blockTag:t,includeTransactions:u});if(A.number!==null&&(d==null?void 0:d.number)!=null){if(A.number===d.number)return;if(A.number-d.number>1&&r)for(let P=(d==null?void 0:d.number)+1n;P<A.number;P++){const w=await ee(e,Gt,"getBlock")({blockNumber:P,includeTransactions:u});b.onBlock(w,d),d=w}}((d==null?void 0:d.number)==null||t==="pending"&&(A==null?void 0:A.number)==null||A.number!==null&&A.number>d.number)&&(b.onBlock(A,d),d=A)}catch(A){(E=b.onError)==null||E.call(b,A)}},{emitOnBegin:n,interval:c}))})():(()=>{let g=!0,b=!0,E=()=>g=!1;return(async()=>{try{n&&ee(e,Gt,"getBlock")({blockTag:t,includeTransactions:u}).then(w=>{g&&b&&(i(w,void 0),b=!1)}).catch(s);const A=(()=>{if(e.transport.type==="fallback"){const w=e.transport.transports.find(_=>_.config.type==="webSocket"||_.config.type==="ipc");return w?w.value:e.transport}return e.transport})(),{unsubscribe:P}=await A.subscribe({params:["newHeads"],async onData(w){var T;if(!g)return;const _=await ee(e,Gt,"getBlock")({blockNumber:(T=w.result)==null?void 0:T.number,includeTransactions:u}).catch(()=>{});g&&(i(_,d),b=!1,d=_)},onError(w){s==null||s(w)}});E=P,g||E()}catch(A){s==null||s(A)}})(),()=>E()})()}function xv(e,{address:t,args:r,batch:n=!0,event:i,events:s,fromBlock:o,onError:a,onLogs:c,poll:f,pollingInterval:u=e.pollingInterval,strict:d}){const y=typeof f<"u"?f:typeof o=="bigint"?!0:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")),p=d??!1;return y?(()=>{const E=Oe(["watchEvent",t,r,n,e.uid,i,u,o]);return ur(E,{onLogs:c,onError:a},A=>{let P;o!==void 0&&(P=o-1n);let w,_=!1;const T=Jn(async()=>{var I;if(!_){try{w=await ee(e,Gh,"createEventFilter")({address:t,args:r,event:i,events:s,strict:p,fromBlock:o})}catch{}_=!0;return}try{let R;if(w)R=await ee(e,go,"getFilterChanges")({filter:w});else{const L=await ee(e,as,"getBlockNumber")({});P&&P!==L?R=await ee(e,Fu,"getLogs")({address:t,args:r,event:i,events:s,fromBlock:P+1n,toBlock:L}):R=[],P=L}if(R.length===0)return;if(n)A.onLogs(R);else for(const L of R)A.onLogs([L])}catch(R){w&&R instanceof Xr&&(_=!1),(I=A.onError)==null||I.call(A,R)}},{emitOnBegin:!0,interval:u});return async()=>{w&&await ee(e,bo,"uninstallFilter")({filter:w}),T()}})})():(()=>{let E=!0,A=()=>E=!1;return(async()=>{try{const P=(()=>{if(e.transport.type==="fallback"){const I=e.transport.transports.find(R=>R.config.type==="webSocket"||R.config.type==="ipc");return I?I.value:e.transport}return e.transport})(),w=s??(i?[i]:void 0);let _=[];w&&(_=[w.flatMap(R=>ts({abi:[R],eventName:R.name,args:r}))],i&&(_=_[0]));const{unsubscribe:T}=await P.subscribe({params:["logs",{address:t,topics:_}],onData(I){var L;if(!E)return;const R=I.result;try{const{eventName:S,args:$}=Ru({abi:w??[],data:R.data,topics:R.topics,strict:p}),C=cr(R,{args:$,eventName:S});c([C])}catch(S){let $,C;if(S instanceof _i||S instanceof Qs){if(d)return;$=S.abiItem.name,C=(L=S.abiItem.inputs)==null?void 0:L.some(j=>!("name"in j&&j.name))}const U=cr(R,{args:C?[]:{},eventName:$});c([U])}},onError(I){a==null||a(I)}});A=T,E||A()}catch(P){a==null||a(P)}})(),()=>A()})()}function Av(e,{batch:t=!0,onError:r,onTransactions:n,poll:i,pollingInterval:s=e.pollingInterval}){return(typeof i<"u"?i:e.transport.type!=="webSocket"&&e.transport.type!=="ipc")?(()=>{const f=Oe(["watchPendingTransactions",e.uid,t,s]);return ur(f,{onTransactions:n,onError:r},u=>{let d;const y=Jn(async()=>{var p;try{if(!d)try{d=await ee(e,Vh,"createPendingTransactionFilter")({});return}catch(b){throw y(),b}const g=await ee(e,go,"getFilterChanges")({filter:d});if(g.length===0)return;if(t)u.onTransactions(g);else for(const b of g)u.onTransactions([b])}catch(g){(p=u.onError)==null||p.call(u,g)}},{emitOnBegin:!0,interval:s});return async()=>{d&&await ee(e,bo,"uninstallFilter")({filter:d}),y()}})})():(()=>{let f=!0,u=()=>f=!1;return(async()=>{try{const{unsubscribe:d}=await e.transport.subscribe({params:["newPendingTransactions"],onData(y){if(!f)return;const p=y.result;n([p])},onError(y){r==null||r(y)}});u=d,f||u()}catch(d){r==null||r(d)}})(),()=>u()})()}function _v(e){var d,y,p;const{scheme:t,statement:r,...n}=((d=e.match(Sv))==null?void 0:d.groups)??{},{chainId:i,expirationTime:s,issuedAt:o,notBefore:a,requestId:c,...f}=((y=e.match(Pv))==null?void 0:y.groups)??{},u=(p=e.split("Resources:")[1])==null?void 0:p.split(`
45
+ - `).slice(1);return{...n,...f,...i?{chainId:Number(i)}:{},...s?{expirationTime:new Date(s)}:{},...o?{issuedAt:new Date(o)}:{},...a?{notBefore:new Date(a)}:{},...c?{requestId:c}:{},...u?{resources:u}:{},...t?{scheme:t}:{},...r?{statement:r}:{}}}const Sv=/^(?:(?<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)?/,Pv=/(?: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 Tv(e){const{address:t,domain:r,message:n,nonce:i,scheme:s,time:o=new Date}=e;if(r&&n.domain!==r||i&&n.nonce!==i||s&&n.scheme!==s||n.expirationTime&&o>=n.expirationTime||n.notBefore&&o<n.notBefore)return!1;try{if(!n.address||!Fe(n.address,{strict:!1})||t&&!ss(n.address,t))return!1}catch{return!1}return!0}async function Iv(e,t){const{address:r,domain:n,message:i,nonce:s,scheme:o,signature:a,time:c=new Date,...f}=t,u=_v(i);if(!u.address||!Tv({address:r,domain:n,message:u,nonce:s,scheme:o,time:c}))return!1;const y=s0(i);return Ju(e,{address:u.address,hash:y,signature:a,...f})}function kv(e){return{call:t=>os(e,t),createAccessList:t=>qh(e,t),createBlockFilter:()=>m1(e),createContractEventFilter:t=>bu(e,t),createEventFilter:t=>Gh(e,t),createPendingTransactionFilter:()=>Vh(e),estimateContractGas:t=>ch(e,t),estimateGas:t=>Cu(e,t),getBalance:t=>ah(e,t),getBlobBaseFee:()=>g1(e),getBlock:t=>Gt(e,t),getBlockNumber:t=>as(e,t),getBlockTransactionCount:t=>b1(e,t),getBytecode:t=>ad(e,t),getChainId:()=>Zn(e),getCode:t=>ad(e,t),getContractEvents:t=>$u(e,t),getEip712Domain:t=>v1(e,t),getEnsAddress:t=>e1(e,t),getEnsAvatar:t=>p1(e,t),getEnsName:t=>h1(e,t),getEnsResolver:t=>y1(e,t),getEnsText:t=>zh(e,t),getFeeHistory:t=>A1(e,t),estimateFeesPerGas:t=>Ob(e,t),getFilterChanges:t=>go(e,t),getFilterLogs:t=>_1(e,t),getGasPrice:()=>Pu(e),getLogs:t=>Fu(e,t),getProof:t=>a2(e,t),estimateMaxPriorityFeePerGas:t=>Bb(e,t),getStorageAt:t=>c2(e,t),getTransaction:t=>Yu(e,t),getTransactionConfirmations:t=>u2(e,t),getTransactionCount:t=>Tu(e,t),getTransactionReceipt:t=>jc(e,t),multicall:t=>f2(e,t),prepareTransactionRequest:t=>lo(e,t),readContract:t=>Wt(e,t),sendRawTransaction:t=>qu(e,t),simulate:t=>zc(e,t),simulateBlocks:t=>zc(e,t),simulateCalls:t=>M2(e,t),simulateContract:t=>Sh(e,t),verifyMessage:t=>bv(e,t),verifySiweMessage:t=>Iv(e,t),verifyTypedData:t=>wv(e,t),uninstallFilter:t=>bo(e,t),waitForTransactionReceipt:t=>vv(e,t),watchBlocks:t=>Ev(e,t),watchBlockNumber:t=>B0(e,t),watchContractEvent:t=>Ph(e,t),watchEvent:t=>xv(e,t),watchPendingTransactions:t=>Av(e,t)}}function Bv(e){const{key:t="public",name:r="Public Client"}=e;return $h({...e,key:t,name:r,type:"publicClient"}).extend(kv)}async function Ov(e,{chain:t}){const{id:r,name:n,nativeCurrency:i,rpcUrls:s,blockExplorers:o}=t;await e.request({method:"wallet_addEthereumChain",params:[{chainId:K(r),chainName:n,nativeCurrency:i,rpcUrls:s.default.http,blockExplorerUrls:o?Object.values(o).map(({url:a})=>a):void 0}]},{dedupe:!0,retryCount:0})}function Cv(e,t){const{abi:r,args:n,bytecode:i,...s}=t,o=mo({abi:r,args:n,bytecode:i});return wo(e,{...s,...s.authorizationList?{to:null}:{},data:o})}async function Rv(e){var r;return((r=e.account)==null?void 0:r.type)==="local"?[e.account.address]:(await e.request({method:"eth_accounts"},{dedupe:!0})).map(n=>Qi(n))}async function Nv(e,t={}){const{account:r=e.account,chainId:n}=t,i=r?ke(r):void 0,s=n?[i==null?void 0:i.address,[K(n)]]:[i==null?void 0:i.address],o=await e.request({method:"wallet_getCapabilities",params:s}),a={};for(const[c,f]of Object.entries(o)){a[Number(c)]={};for(let[u,d]of Object.entries(f))u==="addSubAccount"&&(u="unstable_addSubAccount"),a[Number(c)][u]=d}return typeof n=="number"?a[n]:a}async function Fv(e){return await e.request({method:"wallet_getPermissions"},{dedupe:!0})}async function O0(e,t){var c;const{account:r=e.account,chainId:n,nonce:i}=t;if(!r)throw new cn({docsPath:"/docs/eip7702/prepareAuthorization"});const s=ke(r),o=(()=>{if(t.executor)return t.executor==="self"?t.executor:ke(t.executor)})(),a={address:t.contractAddress??t.address,chainId:n,nonce:i};return typeof a.chainId>"u"&&(a.chainId=((c=e.chain)==null?void 0:c.id)??await ee(e,Zn,"getChainId")({})),typeof a.nonce>"u"&&(a.nonce=await ee(e,Tu,"getTransactionCount")({address:s.address,blockTag:"pending"}),(o==="self"||o!=null&&o.address&&ss(o.address,s.address))&&(a.nonce+=1)),a}async function $v(e){return(await e.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(r=>Tp(r))}async function Uv(e,t){return e.request({method:"wallet_requestPermissions",params:[t]},{retryCount:0})}async function Hv(e,t){const{id:r}=t;await e.request({method:"wallet_showCallsStatus",params:[r]})}async function Lv(e,t){const{account:r=e.account}=t;if(!r)throw new cn({docsPath:"/docs/eip7702/signAuthorization"});const n=ke(r);if(!n.signAuthorization)throw new $s({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});const i=await O0(e,t);return n.signAuthorization(i)}async function Mv(e,{account:t=e.account,message:r}){if(!t)throw new cn({docsPath:"/docs/actions/wallet/signMessage"});const n=ke(t);if(n.signMessage)return n.signMessage({message:r});const i=typeof r=="string"?Rn(r):r.raw instanceof Uint8Array?je(r.raw):r.raw;return e.request({method:"personal_sign",params:[i,n.address]},{retryCount:0})}async function Dv(e,t){var f,u,d,y;const{account:r=e.account,chain:n=e.chain,...i}=t;if(!r)throw new cn({docsPath:"/docs/actions/wallet/signTransaction"});const s=ke(r);on({account:s,...t});const o=await ee(e,Zn,"getChainId")({});n!==null&&Th({currentChainId:o,chain:n});const a=(n==null?void 0:n.formatters)||((f=e.chain)==null?void 0:f.formatters),c=((u=a==null?void 0:a.transactionRequest)==null?void 0:u.format)||Yn;return s.signTransaction?s.signTransaction({...i,chainId:o},{serializer:(y=(d=e.chain)==null?void 0:d.serializers)==null?void 0:y.transaction}):await e.request({method:"eth_signTransaction",params:[{...c(i),chainId:K(o),from:s.address}]},{retryCount:0})}async function jv(e,t){const{account:r=e.account,domain:n,message:i,primaryType:s}=t;if(!r)throw new cn({docsPath:"/docs/actions/wallet/signTypedData"});const o=ke(r),a={EIP712Domain:Jh({domain:n}),...t.types};if(Xh({domain:n,message:i,primaryType:s,types:a}),o.signTypedData)return o.signTypedData({domain:n,message:i,primaryType:s,types:a});const c=C1({domain:n,message:i,primaryType:s,types:a});return e.request({method:"eth_signTypedData_v4",params:[o.address,c]},{retryCount:0})}async function zv(e,{id:t}){await e.request({method:"wallet_switchEthereumChain",params:[{chainId:K(t)}]},{retryCount:0})}async function qv(e,t){return await e.request({method:"wallet_watchAsset",params:t},{retryCount:0})}function Gv(e){return{addChain:t=>Ov(e,t),deployContract:t=>Cv(e,t),getAddresses:()=>Rv(e),getCallsStatus:t=>Nh(e,t),getCapabilities:t=>Nv(e,t),getChainId:()=>Zn(e),getPermissions:()=>Fv(e),prepareAuthorization:t=>O0(e,t),prepareTransactionRequest:t=>lo(e,t),requestAddresses:()=>$v(e),requestPermissions:t=>Uv(e,t),sendCalls:t=>Lw(e,t),sendRawTransaction:t=>qu(e,t),sendTransaction:t=>wo(e,t),showCallsStatus:t=>Hv(e,t),signAuthorization:t=>Lv(e,t),signMessage:t=>Mv(e,t),signTransaction:t=>Dv(e,t),signTypedData:t=>jv(e,t),switchChain:t=>zv(e,t),waitForCallsStatus:t=>Mw(e,t),watchAsset:t=>qv(e,t),writeContract:t=>kh(e,t)}}function ra(e){const{key:t="wallet",name:r="Wallet Client",transport:n}=e;return $h({...e,key:t,name:r,transport:n,type:"walletClient"}).extend(Gv)}const Hs={mainnet:{orderbook:"https://api.garden.finance",auth:"https://api.garden.finance/auth",quote:"https://api.garden.finance/quote",info:"https://api.garden.finance/info",evmRelay:"https://api.garden.finance/relayer",solanaRelay:"https://solana-relayer.garden.finance/",starknetRelay:"https://api.garden.finance/starknet"},testnet:{orderbook:"https://testnet.api.garden.finance",auth:"https://testnet.api.garden.finance/auth",quote:"https://testnet.api.garden.finance/quote",info:"https://testnet.api.garden.finance/info",evmRelay:"https://testnet.api.garden.finance/relayer",solanaRelay:"https://solana-relay.garden.finance",starknetRelay:"https://testnet.api.garden.finance/starknet"},localnet:{orderbook:"",auth:"",quote:"",info:"",evmRelay:"",starknetRelay:"",solanaRelay:""}},Wi={[x.Network.MAINNET]:{chainId:"0x534e5f4d41494e",nodeUrl:"https://starknet-mainnet.public.blastapi.io/rpc/v0_8"},[x.Network.TESTNET]:{chainId:"0x534e5f5345504f4c4941",nodeUrl:"https://starknet-sepolia.public.blastapi.io/rpc/v0_8"},[x.Network.LOCALNET]:{chainId:"",nodeUrl:""}},Xc={[x.Network.MAINNET]:"9cBuPNiHXiMNg3Fin8xLCGJQBTXjYQTFtyaFQv2uiM1H",[x.Network.TESTNET]:"ANUVKxeqaec3bf4DVPqLTnG1PT3Fng56wPcE7LXAb46Q",[x.Network.LOCALNET]:"AKnL4NNf3DGWZJS6cPknBuEGnVsV4A4m5tgebLHaRSZ9"},C0={mainnet:"2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",staging:"6eksgdCnSjUaGQWZ6iYvauv1qzvYPF33RTGTM1ZuyENx"},gd={chain:le.SupportedAssets.mainnet.base_cbBTC.chain,asset:le.SupportedAssets.mainnet.base_cbBTC.atomicSwapAddress};var In=(e=>(e.SLOW="SLOW",e.MEDIUM="MEDIUM",e.FAST="FAST",e))(In||{}),ct=(e=>(e.Mainnet="Mainnet",e.Testnet="Testnet",e.Regtest="Regtest",e))(ct||{}),Ls=(e=>(e.ALL="ALL",e.IN="IN",e.OUT="OUT",e))(Ls||{});const Vv={SLOW:"economyFee",MEDIUM:"hourFee",FAST:"fastestFee"};function Jc(e){const t=typeof e=="string"?e:e.environment,r=t===x.Environment.MAINNET?Hs.mainnet:x.Environment.TESTNET?Hs.testnet:Hs.localnet;return{api:typeof e=="string"?r:{...r,...e},environment:t}}function Qc(e){return typeof e=="string"&&(e=Buffer.from(e,"hex")),e.length===32?e:e.subarray(1,33)}function yn(e,t){if(!e)throw new Error(t)}function Wv(e){return Buffer.concat([Uint8Array.from([192]),Kv(e)])}function Kv(e){const t=xf.encodingLength(e.length),r=Buffer.allocUnsafe(t);return xf.encode(e.length,r),Buffer.concat([r,e])}function Yv(e,t){if(e.compare(t)>0){const r=e;e=t,t=r}return[e,t]}const Ar=e=>e.length===64?e:e.slice(2),Zv=e=>{if(!e)return!1;try{const t=Buffer.from(e,"hex");return wt.isPoint(t)}catch{return!1}},eu=(e,t,r,n)=>e+":"+t.toLowerCase()+"::"+r+":"+n.toLowerCase();function Xv(e,t){if(!e)return!1;const r=t===x.Environment.MAINNET?pe.networks.bitcoin:t===x.Environment.TESTNET?pe.networks.testnet:pe.networks.regtest;if(!r)return!1;pe.initEccLib(wt);try{return pe.address.toOutputScript(e,r),!0}catch{return!1}}const Jv=e=>{switch(e){case x.Environment.MAINNET:return ct.Mainnet;case x.Environment.TESTNET:return ct.Testnet;case x.Environment.LOCALNET:return ct.Regtest;default:throw new Error(`Invalid bitcoin network ${e}`)}},Qv=e=>{const t=e.toLowerCase().replace("0x","");return/^[0-9a-f]+$/.test(t)},eE=e=>{if(typeof e=="object"&&"r"in e&&"s"in e)return x.Ok([e.r.toString(),e.s.toString()]);if(Array.isArray(e)){const t=e.map(r=>typeof r=="string"&&r.startsWith("0x")&&Qv(r)?BigInt(r).toString():r);return x.Ok(t)}return x.Err("Invalid signature format")};function tu(e){return Buffer.from(e,"hex").reverse()}function ru(e){return typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"}const bd=async(e,t)=>{const r=Date.now(),n=3e4,i=2e3;for(;Date.now()-r<n;){const s=await e.getLatestBlockhash(),o=await e.confirmTransaction({signature:t,blockhash:s.blockhash,lastValidBlockHeight:s.lastValidBlockHeight},"confirmed");if(o.value&&o.value.err==null)return console.log("Tx Confirmed ✅"),!0;console.log("Tx not confirmed yet. Retrying in 2 seconds..."),await new Promise(a=>setTimeout(a,i))}return!1};var fe=(e=>(e.Created="Created",e.Matched="Matched",e.InitiateDetected="InitiateDetected",e.Initiated="Initiated",e.CounterPartyInitiateDetected="CounterPartyInitiateDetected",e.CounterPartyInitiated="CounterPartyInitiated",e.RedeemDetected="RedeemDetected",e.Redeemed="Redeemed",e.CounterPartyRedeemDetected="CounterPartyRedeemDetected",e.CounterPartyRedeemed="CounterPartyRedeemed",e.Completed="Completed",e.CounterPartySwapExpired="CounterPartySwapExpired",e.Expired="Expired",e.RefundDetected="RefundDetected",e.Refunded="Refunded",e.CounterPartyRefundDetected="CounterPartyRefundDetected",e.CounterPartyRefunded="CounterPartyRefunded",e.Cancelled="Cancelled",e.DeadLineExceeded="DeadLineExceeded",e))(fe||{}),Ee=(e=>(e.Idle="Idle",e.InitiateDetected="InitiateDetected",e.Initiated="Initiated",e.RedeemDetected="RedeemDetected",e.Redeemed="Redeemed",e.RefundDetected="RefundDetected",e.Refunded="Refunded",e.Expired="Expired",e))(Ee||{});const Qu=(e,t,r)=>{const n=nu(e.source_swap,t),i=nu(e.destination_swap,r);if(i===Ee.RedeemDetected)return fe.RedeemDetected;if(i===Ee.Redeemed)return fe.Redeemed;if(n===Ee.Refunded)return fe.Refunded;if(n===Ee.RefundDetected)return fe.RefundDetected;if(i===Ee.Expired)return fe.CounterPartySwapExpired;if(n===Ee.Expired)return fe.Expired;if(i===Ee.Refunded)return fe.CounterPartyRefunded;if(i===Ee.RefundDetected)return fe.CounterPartyRefundDetected;const s=Number(e.create_order.additional_data.deadline);return i===Ee.Initiated?fe.CounterPartyInitiated:i===Ee.InitiateDetected?fe.CounterPartyInitiateDetected:Ki(s,12)?fe.DeadLineExceeded:n===Ee.Initiated?fe.Initiated:Ki(s,1)?fe.DeadLineExceeded:n===Ee.InitiateDetected?fe.InitiateDetected:n===Ee.Redeemed?fe.CounterPartyRedeemed:n===Ee.RedeemDetected?fe.CounterPartyRedeemDetected:fe.Matched},nu=(e,t)=>{if(e.redeem_tx_hash)return Number(e.redeem_block_number)?Ee.Redeemed:Ee.RedeemDetected;if(e.refund_tx_hash)return Number(e.refund_block_number)?Ee.Refunded:Ee.RefundDetected;if(Number(e.initiate_block_number)){const r=Number(e.initiate_block_number)+e.timelock;if(t>r)return Ee.Expired}return e.initiate_tx_hash?Number(e.initiate_block_number)?Ee.Initiated:Ee.InitiateDetected:Ee.Idle},tE=(e,t,r)=>{const n=Qu(e,t,r);return ef(n)},ef=e=>{switch(e){case fe.Matched:return ve.Initiate;case fe.CounterPartyInitiated:case fe.CounterPartyInitiateDetected:case fe.RedeemDetected:return ve.Redeem;case fe.Expired:return ve.Refund;default:return ve.Idle}},Ki=(e,t=0)=>{const r=Date.now(),n=e*1e3+t*36e5;return r>=n},rE=e=>e.filter(t=>!R0(t)),R0=e=>{const{source_swap:t,create_order:r}=e,{initiate_tx_hash:n,initiate_block_number:i}=t,{deadline:s}=r.additional_data;return n&&Number(i)?!1:n&&!Number(i)?Ki(Number(s),12):n?!1:Ki(Number(s),1)},nE=Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),iE=Buffer.from("483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8","hex"),sE=Buffer.concat([nE,iE]),oE=Buffer.from("0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0","hex"),wd={failedToCreateInternalPubkey:"failed to create internal pubkey"};function aE(){const e=oe.crypto.sha256(Buffer.from("GardenHTLC","utf-8")),t=wt.pointMultiply(Buffer.concat([Buffer.from("04","hex"),sE]),e);if(!t)throw new Error(wd.failedToCreateInternalPubkey);const r=wt.pointAdd(oE,t);if(!r)throw new Error(wd.failedToCreateInternalPubkey);return Qc(Buffer.from(r))}var Kt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function N0(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var r=function n(){return this instanceof n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}),r}var _e={},qe={},un={},So={};So.byteLength=fE;So.toByteArray=lE;So.fromByteArray=yE;var qt=[],gt=[],cE=typeof Uint8Array<"u"?Uint8Array:Array,na="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var mn=0,uE=na.length;mn<uE;++mn)qt[mn]=na[mn],gt[na.charCodeAt(mn)]=mn;gt[45]=62;gt[95]=63;function F0(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var n=r===t?0:4-r%4;return[r,n]}function fE(e){var t=F0(e),r=t[0],n=t[1];return(r+n)*3/4-n}function dE(e,t,r){return(t+r)*3/4-r}function lE(e){var t,r=F0(e),n=r[0],i=r[1],s=new cE(dE(e,n,i)),o=0,a=i>0?n-4:n,c;for(c=0;c<a;c+=4)t=gt[e.charCodeAt(c)]<<18|gt[e.charCodeAt(c+1)]<<12|gt[e.charCodeAt(c+2)]<<6|gt[e.charCodeAt(c+3)],s[o++]=t>>16&255,s[o++]=t>>8&255,s[o++]=t&255;return i===2&&(t=gt[e.charCodeAt(c)]<<2|gt[e.charCodeAt(c+1)]>>4,s[o++]=t&255),i===1&&(t=gt[e.charCodeAt(c)]<<10|gt[e.charCodeAt(c+1)]<<4|gt[e.charCodeAt(c+2)]>>2,s[o++]=t>>8&255,s[o++]=t&255),s}function pE(e){return qt[e>>18&63]+qt[e>>12&63]+qt[e>>6&63]+qt[e&63]}function hE(e,t,r){for(var n,i=[],s=t;s<r;s+=3)n=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(e[s+2]&255),i.push(pE(n));return i.join("")}function yE(e){for(var t,r=e.length,n=r%3,i=[],s=16383,o=0,a=r-n;o<a;o+=s)i.push(hE(e,o,o+s>a?a:o+s));return n===1?(t=e[r-1],i.push(qt[t>>2]+qt[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],i.push(qt[t>>10]+qt[t>>4&63]+qt[t<<2&63]+"=")),i.join("")}var tf={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */tf.read=function(e,t,r,n,i){var s,o,a=i*8-n-1,c=(1<<a)-1,f=c>>1,u=-7,d=r?i-1:0,y=r?-1:1,p=e[t+d];for(d+=y,s=p&(1<<-u)-1,p>>=-u,u+=a;u>0;s=s*256+e[t+d],d+=y,u-=8);for(o=s&(1<<-u)-1,s>>=-u,u+=n;u>0;o=o*256+e[t+d],d+=y,u-=8);if(s===0)s=1-f;else{if(s===c)return o?NaN:(p?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-f}return(p?-1:1)*o*Math.pow(2,s-n)};tf.write=function(e,t,r,n,i,s){var o,a,c,f=s*8-i-1,u=(1<<f)-1,d=u>>1,y=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:s-1,g=n?1:-1,b=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+d>=1?t+=y/c:t+=y*Math.pow(2,1-d),t*c>=2&&(o++,c/=2),o+d>=u?(a=0,o=u):o+d>=1?(a=(t*c-1)*Math.pow(2,i),o=o+d):(a=t*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;e[r+p]=a&255,p+=g,a/=256,i-=8);for(o=o<<i|a,f+=i;f>0;e[r+p]=o&255,p+=g,o/=256,f-=8);e[r+p-g]|=b*128};/*!
46
46
  * The buffer module from node.js, for the browser.
47
47
  *
48
48
  * @author Feross Aboukhadijeh <https://feross.org>
49
49
  * @license MIT
50
- */(function(e){const t=So,r=tf,n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=a,e.SlowBuffer=P,e.INSPECT_MAX_BYTES=50;const i=2147483647;e.kMaxLength=i,a.TYPED_ARRAY_SUPPORT=s(),!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 s(){try{const m=new Uint8Array(1),l={foo:function(){return 42}};return Object.setPrototypeOf(l,Uint8Array.prototype),Object.setPrototypeOf(m,l),m.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(m){if(m>i)throw new RangeError('The value "'+m+'" is invalid for option "size"');const l=new Uint8Array(m);return Object.setPrototypeOf(l,a.prototype),l}function a(m,l,h){if(typeof m=="number"){if(typeof l=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return d(m)}return c(m,l,h)}a.poolSize=8192;function c(m,l,h){if(typeof m=="string")return y(m,l);if(ArrayBuffer.isView(m))return g(m);if(m==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof m);if(Ve(m,ArrayBuffer)||m&&Ve(m.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Ve(m,SharedArrayBuffer)||m&&Ve(m.buffer,SharedArrayBuffer)))return b(m,l,h);if(typeof m=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const v=m.valueOf&&m.valueOf();if(v!=null&&v!==m)return a.from(v,l,h);const O=E(m);if(O)return O;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof m[Symbol.toPrimitive]=="function")return a.from(m[Symbol.toPrimitive]("string"),l,h);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof m)}a.from=function(m,l,h){return c(m,l,h)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function f(m){if(typeof m!="number")throw new TypeError('"size" argument must be of type number');if(m<0)throw new RangeError('The value "'+m+'" is invalid for option "size"')}function u(m,l,h){return f(m),m<=0?o(m):l!==void 0?typeof h=="string"?o(m).fill(l,h):o(m).fill(l):o(m)}a.alloc=function(m,l,h){return u(m,l,h)};function d(m){return f(m),o(m<0?0:A(m)|0)}a.allocUnsafe=function(m){return d(m)},a.allocUnsafeSlow=function(m){return d(m)};function y(m,l){if((typeof l!="string"||l==="")&&(l="utf8"),!a.isEncoding(l))throw new TypeError("Unknown encoding: "+l);const h=w(m,l)|0;let v=o(h);const O=v.write(m,l);return O!==h&&(v=v.slice(0,O)),v}function p(m){const l=m.length<0?0:A(m.length)|0,h=o(l);for(let v=0;v<l;v+=1)h[v]=m[v]&255;return h}function g(m){if(Ve(m,Uint8Array)){const l=new Uint8Array(m);return b(l.buffer,l.byteOffset,l.byteLength)}return p(m)}function b(m,l,h){if(l<0||m.byteLength<l)throw new RangeError('"offset" is outside of buffer bounds');if(m.byteLength<l+(h||0))throw new RangeError('"length" is outside of buffer bounds');let v;return l===void 0&&h===void 0?v=new Uint8Array(m):h===void 0?v=new Uint8Array(m,l):v=new Uint8Array(m,l,h),Object.setPrototypeOf(v,a.prototype),v}function E(m){if(a.isBuffer(m)){const l=A(m.length)|0,h=o(l);return h.length===0||m.copy(h,0,0,l),h}if(m.length!==void 0)return typeof m.length!="number"||hr(m.length)?o(0):p(m);if(m.type==="Buffer"&&Array.isArray(m.data))return p(m.data)}function A(m){if(m>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return m|0}function P(m){return+m!=m&&(m=0),a.alloc(+m)}a.isBuffer=function(l){return l!=null&&l._isBuffer===!0&&l!==a.prototype},a.compare=function(l,h){if(Ve(l,Uint8Array)&&(l=a.from(l,l.offset,l.byteLength)),Ve(h,Uint8Array)&&(h=a.from(h,h.offset,h.byteLength)),!a.isBuffer(l)||!a.isBuffer(h))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(l===h)return 0;let v=l.length,O=h.length;for(let F=0,z=Math.min(v,O);F<z;++F)if(l[F]!==h[F]){v=l[F],O=h[F];break}return v<O?-1:O<v?1:0},a.isEncoding=function(l){switch(String(l).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(l,h){if(!Array.isArray(l))throw new TypeError('"list" argument must be an Array of Buffers');if(l.length===0)return a.alloc(0);let v;if(h===void 0)for(h=0,v=0;v<l.length;++v)h+=l[v].length;const O=a.allocUnsafe(h);let F=0;for(v=0;v<l.length;++v){let z=l[v];if(Ve(z,Uint8Array))F+z.length>O.length?(a.isBuffer(z)||(z=a.from(z)),z.copy(O,F)):Uint8Array.prototype.set.call(O,z,F);else if(a.isBuffer(z))z.copy(O,F);else throw new TypeError('"list" argument must be an Array of Buffers');F+=z.length}return O};function w(m,l){if(a.isBuffer(m))return m.length;if(ArrayBuffer.isView(m)||Ve(m,ArrayBuffer))return m.byteLength;if(typeof m!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof m);const h=m.length,v=arguments.length>2&&arguments[2]===!0;if(!v&&h===0)return 0;let O=!1;for(;;)switch(l){case"ascii":case"latin1":case"binary":return h;case"utf8":case"utf-8":return Rt(m).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return h*2;case"hex":return h>>>1;case"base64":return Nt(m).length;default:if(O)return v?-1:Rt(m).length;l=(""+l).toLowerCase(),O=!0}}a.byteLength=w;function _(m,l,h){let v=!1;if((l===void 0||l<0)&&(l=0),l>this.length||((h===void 0||h>this.length)&&(h=this.length),h<=0)||(h>>>=0,l>>>=0,h<=l))return"";for(m||(m="utf8");;)switch(m){case"hex":return B(this,l,h);case"utf8":case"utf-8":return V(this,l,h);case"ascii":return J(this,l,h);case"latin1":case"binary":return M(this,l,h);case"base64":return j(this,l,h);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return q(this,l,h);default:if(v)throw new TypeError("Unknown encoding: "+m);m=(m+"").toLowerCase(),v=!0}}a.prototype._isBuffer=!0;function T(m,l,h){const v=m[l];m[l]=m[h],m[h]=v}a.prototype.swap16=function(){const l=this.length;if(l%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let h=0;h<l;h+=2)T(this,h,h+1);return this},a.prototype.swap32=function(){const l=this.length;if(l%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let h=0;h<l;h+=4)T(this,h,h+3),T(this,h+1,h+2);return this},a.prototype.swap64=function(){const l=this.length;if(l%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let h=0;h<l;h+=8)T(this,h,h+7),T(this,h+1,h+6),T(this,h+2,h+5),T(this,h+3,h+4);return this},a.prototype.toString=function(){const l=this.length;return l===0?"":arguments.length===0?V(this,0,l):_.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(l){if(!a.isBuffer(l))throw new TypeError("Argument must be a Buffer");return this===l?!0:a.compare(this,l)===0},a.prototype.inspect=function(){let l="";const h=e.INSPECT_MAX_BYTES;return l=this.toString("hex",0,h).replace(/(.{2})/g,"$1 ").trim(),this.length>h&&(l+=" ... "),"<Buffer "+l+">"},n&&(a.prototype[n]=a.prototype.inspect),a.prototype.compare=function(l,h,v,O,F){if(Ve(l,Uint8Array)&&(l=a.from(l,l.offset,l.byteLength)),!a.isBuffer(l))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof l);if(h===void 0&&(h=0),v===void 0&&(v=l?l.length:0),O===void 0&&(O=0),F===void 0&&(F=this.length),h<0||v>l.length||O<0||F>this.length)throw new RangeError("out of range index");if(O>=F&&h>=v)return 0;if(O>=F)return-1;if(h>=v)return 1;if(h>>>=0,v>>>=0,O>>>=0,F>>>=0,this===l)return 0;let z=F-O,ce=v-h;const Pe=Math.min(z,ce),we=this.slice(O,F),Te=l.slice(h,v);for(let ye=0;ye<Pe;++ye)if(we[ye]!==Te[ye]){z=we[ye],ce=Te[ye];break}return z<ce?-1:ce<z?1:0};function I(m,l,h,v,O){if(m.length===0)return-1;if(typeof h=="string"?(v=h,h=0):h>2147483647?h=2147483647:h<-2147483648&&(h=-2147483648),h=+h,hr(h)&&(h=O?0:m.length-1),h<0&&(h=m.length+h),h>=m.length){if(O)return-1;h=m.length-1}else if(h<0)if(O)h=0;else return-1;if(typeof l=="string"&&(l=a.from(l,v)),a.isBuffer(l))return l.length===0?-1:R(m,l,h,v,O);if(typeof l=="number")return l=l&255,typeof Uint8Array.prototype.indexOf=="function"?O?Uint8Array.prototype.indexOf.call(m,l,h):Uint8Array.prototype.lastIndexOf.call(m,l,h):R(m,[l],h,v,O);throw new TypeError("val must be string, number or Buffer")}function R(m,l,h,v,O){let F=1,z=m.length,ce=l.length;if(v!==void 0&&(v=String(v).toLowerCase(),v==="ucs2"||v==="ucs-2"||v==="utf16le"||v==="utf-16le")){if(m.length<2||l.length<2)return-1;F=2,z/=2,ce/=2,h/=2}function Pe(Te,ye){return F===1?Te[ye]:Te.readUInt16BE(ye*F)}let we;if(O){let Te=-1;for(we=h;we<z;we++)if(Pe(m,we)===Pe(l,Te===-1?0:we-Te)){if(Te===-1&&(Te=we),we-Te+1===ce)return Te*F}else Te!==-1&&(we-=we-Te),Te=-1}else for(h+ce>z&&(h=z-ce),we=h;we>=0;we--){let Te=!0;for(let ye=0;ye<ce;ye++)if(Pe(m,we+ye)!==Pe(l,ye)){Te=!1;break}if(Te)return we}return-1}a.prototype.includes=function(l,h,v){return this.indexOf(l,h,v)!==-1},a.prototype.indexOf=function(l,h,v){return I(this,l,h,v,!0)},a.prototype.lastIndexOf=function(l,h,v){return I(this,l,h,v,!1)};function L(m,l,h,v){h=Number(h)||0;const O=m.length-h;v?(v=Number(v),v>O&&(v=O)):v=O;const F=l.length;v>F/2&&(v=F/2);let z;for(z=0;z<v;++z){const ce=parseInt(l.substr(z*2,2),16);if(hr(ce))return z;m[h+z]=ce}return z}function S(m,l,h,v){return Ge(Rt(l,m.length-h),m,h,v)}function $(m,l,h,v){return Ge(Fr(l),m,h,v)}function C(m,l,h,v){return Ge(Nt(l),m,h,v)}function U(m,l,h,v){return Ge(G(l,m.length-h),m,h,v)}a.prototype.write=function(l,h,v,O){if(h===void 0)O="utf8",v=this.length,h=0;else if(v===void 0&&typeof h=="string")O=h,v=this.length,h=0;else if(isFinite(h))h=h>>>0,isFinite(v)?(v=v>>>0,O===void 0&&(O="utf8")):(O=v,v=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const F=this.length-h;if((v===void 0||v>F)&&(v=F),l.length>0&&(v<0||h<0)||h>this.length)throw new RangeError("Attempt to write outside buffer bounds");O||(O="utf8");let z=!1;for(;;)switch(O){case"hex":return L(this,l,h,v);case"utf8":case"utf-8":return S(this,l,h,v);case"ascii":case"latin1":case"binary":return $(this,l,h,v);case"base64":return C(this,l,h,v);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return U(this,l,h,v);default:if(z)throw new TypeError("Unknown encoding: "+O);O=(""+O).toLowerCase(),z=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function j(m,l,h){return l===0&&h===m.length?t.fromByteArray(m):t.fromByteArray(m.slice(l,h))}function V(m,l,h){h=Math.min(m.length,h);const v=[];let O=l;for(;O<h;){const F=m[O];let z=null,ce=F>239?4:F>223?3:F>191?2:1;if(O+ce<=h){let Pe,we,Te,ye;switch(ce){case 1:F<128&&(z=F);break;case 2:Pe=m[O+1],(Pe&192)===128&&(ye=(F&31)<<6|Pe&63,ye>127&&(z=ye));break;case 3:Pe=m[O+1],we=m[O+2],(Pe&192)===128&&(we&192)===128&&(ye=(F&15)<<12|(Pe&63)<<6|we&63,ye>2047&&(ye<55296||ye>57343)&&(z=ye));break;case 4:Pe=m[O+1],we=m[O+2],Te=m[O+3],(Pe&192)===128&&(we&192)===128&&(Te&192)===128&&(ye=(F&15)<<18|(Pe&63)<<12|(we&63)<<6|Te&63,ye>65535&&ye<1114112&&(z=ye))}}z===null?(z=65533,ce=1):z>65535&&(z-=65536,v.push(z>>>10&1023|55296),z=56320|z&1023),v.push(z),O+=ce}return X(v)}const Y=4096;function X(m){const l=m.length;if(l<=Y)return String.fromCharCode.apply(String,m);let h="",v=0;for(;v<l;)h+=String.fromCharCode.apply(String,m.slice(v,v+=Y));return h}function J(m,l,h){let v="";h=Math.min(m.length,h);for(let O=l;O<h;++O)v+=String.fromCharCode(m[O]&127);return v}function M(m,l,h){let v="";h=Math.min(m.length,h);for(let O=l;O<h;++O)v+=String.fromCharCode(m[O]);return v}function B(m,l,h){const v=m.length;(!l||l<0)&&(l=0),(!h||h<0||h>v)&&(h=v);let O="";for(let F=l;F<h;++F)O+=ln[m[F]];return O}function q(m,l,h){const v=m.slice(l,h);let O="";for(let F=0;F<v.length-1;F+=2)O+=String.fromCharCode(v[F]+v[F+1]*256);return O}a.prototype.slice=function(l,h){const v=this.length;l=~~l,h=h===void 0?v:~~h,l<0?(l+=v,l<0&&(l=0)):l>v&&(l=v),h<0?(h+=v,h<0&&(h=0)):h>v&&(h=v),h<l&&(h=l);const O=this.subarray(l,h);return Object.setPrototypeOf(O,a.prototype),O};function W(m,l,h){if(m%1!==0||m<0)throw new RangeError("offset is not uint");if(m+l>h)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(l,h,v){l=l>>>0,h=h>>>0,v||W(l,h,this.length);let O=this[l],F=1,z=0;for(;++z<h&&(F*=256);)O+=this[l+z]*F;return O},a.prototype.readUintBE=a.prototype.readUIntBE=function(l,h,v){l=l>>>0,h=h>>>0,v||W(l,h,this.length);let O=this[l+--h],F=1;for(;h>0&&(F*=256);)O+=this[l+--h]*F;return O},a.prototype.readUint8=a.prototype.readUInt8=function(l,h){return l=l>>>0,h||W(l,1,this.length),this[l]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(l,h){return l=l>>>0,h||W(l,2,this.length),this[l]|this[l+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(l,h){return l=l>>>0,h||W(l,2,this.length),this[l]<<8|this[l+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(l,h){return l=l>>>0,h||W(l,4,this.length),(this[l]|this[l+1]<<8|this[l+2]<<16)+this[l+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(l,h){return l=l>>>0,h||W(l,4,this.length),this[l]*16777216+(this[l+1]<<16|this[l+2]<<8|this[l+3])},a.prototype.readBigUInt64LE=yr(function(l){l=l>>>0,he(l,"offset");const h=this[l],v=this[l+7];(h===void 0||v===void 0)&&Ae(l,this.length-8);const O=h+this[++l]*2**8+this[++l]*2**16+this[++l]*2**24,F=this[++l]+this[++l]*2**8+this[++l]*2**16+v*2**24;return BigInt(O)+(BigInt(F)<<BigInt(32))}),a.prototype.readBigUInt64BE=yr(function(l){l=l>>>0,he(l,"offset");const h=this[l],v=this[l+7];(h===void 0||v===void 0)&&Ae(l,this.length-8);const O=h*2**24+this[++l]*2**16+this[++l]*2**8+this[++l],F=this[++l]*2**24+this[++l]*2**16+this[++l]*2**8+v;return(BigInt(O)<<BigInt(32))+BigInt(F)}),a.prototype.readIntLE=function(l,h,v){l=l>>>0,h=h>>>0,v||W(l,h,this.length);let O=this[l],F=1,z=0;for(;++z<h&&(F*=256);)O+=this[l+z]*F;return F*=128,O>=F&&(O-=Math.pow(2,8*h)),O},a.prototype.readIntBE=function(l,h,v){l=l>>>0,h=h>>>0,v||W(l,h,this.length);let O=h,F=1,z=this[l+--O];for(;O>0&&(F*=256);)z+=this[l+--O]*F;return F*=128,z>=F&&(z-=Math.pow(2,8*h)),z},a.prototype.readInt8=function(l,h){return l=l>>>0,h||W(l,1,this.length),this[l]&128?(255-this[l]+1)*-1:this[l]},a.prototype.readInt16LE=function(l,h){l=l>>>0,h||W(l,2,this.length);const v=this[l]|this[l+1]<<8;return v&32768?v|4294901760:v},a.prototype.readInt16BE=function(l,h){l=l>>>0,h||W(l,2,this.length);const v=this[l+1]|this[l]<<8;return v&32768?v|4294901760:v},a.prototype.readInt32LE=function(l,h){return l=l>>>0,h||W(l,4,this.length),this[l]|this[l+1]<<8|this[l+2]<<16|this[l+3]<<24},a.prototype.readInt32BE=function(l,h){return l=l>>>0,h||W(l,4,this.length),this[l]<<24|this[l+1]<<16|this[l+2]<<8|this[l+3]},a.prototype.readBigInt64LE=yr(function(l){l=l>>>0,he(l,"offset");const h=this[l],v=this[l+7];(h===void 0||v===void 0)&&Ae(l,this.length-8);const O=this[l+4]+this[l+5]*2**8+this[l+6]*2**16+(v<<24);return(BigInt(O)<<BigInt(32))+BigInt(h+this[++l]*2**8+this[++l]*2**16+this[++l]*2**24)}),a.prototype.readBigInt64BE=yr(function(l){l=l>>>0,he(l,"offset");const h=this[l],v=this[l+7];(h===void 0||v===void 0)&&Ae(l,this.length-8);const O=(h<<24)+this[++l]*2**16+this[++l]*2**8+this[++l];return(BigInt(O)<<BigInt(32))+BigInt(this[++l]*2**24+this[++l]*2**16+this[++l]*2**8+v)}),a.prototype.readFloatLE=function(l,h){return l=l>>>0,h||W(l,4,this.length),r.read(this,l,!0,23,4)},a.prototype.readFloatBE=function(l,h){return l=l>>>0,h||W(l,4,this.length),r.read(this,l,!1,23,4)},a.prototype.readDoubleLE=function(l,h){return l=l>>>0,h||W(l,8,this.length),r.read(this,l,!0,52,8)},a.prototype.readDoubleBE=function(l,h){return l=l>>>0,h||W(l,8,this.length),r.read(this,l,!1,52,8)};function k(m,l,h,v,O,F){if(!a.isBuffer(m))throw new TypeError('"buffer" argument must be a Buffer instance');if(l>O||l<F)throw new RangeError('"value" argument is out of bounds');if(h+v>m.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(l,h,v,O){if(l=+l,h=h>>>0,v=v>>>0,!O){const ce=Math.pow(2,8*v)-1;k(this,l,h,v,ce,0)}let F=1,z=0;for(this[h]=l&255;++z<v&&(F*=256);)this[h+z]=l/F&255;return h+v},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(l,h,v,O){if(l=+l,h=h>>>0,v=v>>>0,!O){const ce=Math.pow(2,8*v)-1;k(this,l,h,v,ce,0)}let F=v-1,z=1;for(this[h+F]=l&255;--F>=0&&(z*=256);)this[h+F]=l/z&255;return h+v},a.prototype.writeUint8=a.prototype.writeUInt8=function(l,h,v){return l=+l,h=h>>>0,v||k(this,l,h,1,255,0),this[h]=l&255,h+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(l,h,v){return l=+l,h=h>>>0,v||k(this,l,h,2,65535,0),this[h]=l&255,this[h+1]=l>>>8,h+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(l,h,v){return l=+l,h=h>>>0,v||k(this,l,h,2,65535,0),this[h]=l>>>8,this[h+1]=l&255,h+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(l,h,v){return l=+l,h=h>>>0,v||k(this,l,h,4,4294967295,0),this[h+3]=l>>>24,this[h+2]=l>>>16,this[h+1]=l>>>8,this[h]=l&255,h+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(l,h,v){return l=+l,h=h>>>0,v||k(this,l,h,4,4294967295,0),this[h]=l>>>24,this[h+1]=l>>>16,this[h+2]=l>>>8,this[h+3]=l&255,h+4};function N(m,l,h,v,O){de(l,v,O,m,h,7);let F=Number(l&BigInt(4294967295));m[h++]=F,F=F>>8,m[h++]=F,F=F>>8,m[h++]=F,F=F>>8,m[h++]=F;let z=Number(l>>BigInt(32)&BigInt(4294967295));return m[h++]=z,z=z>>8,m[h++]=z,z=z>>8,m[h++]=z,z=z>>8,m[h++]=z,h}function H(m,l,h,v,O){de(l,v,O,m,h,7);let F=Number(l&BigInt(4294967295));m[h+7]=F,F=F>>8,m[h+6]=F,F=F>>8,m[h+5]=F,F=F>>8,m[h+4]=F;let z=Number(l>>BigInt(32)&BigInt(4294967295));return m[h+3]=z,z=z>>8,m[h+2]=z,z=z>>8,m[h+1]=z,z=z>>8,m[h]=z,h+8}a.prototype.writeBigUInt64LE=yr(function(l,h=0){return N(this,l,h,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=yr(function(l,h=0){return H(this,l,h,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(l,h,v,O){if(l=+l,h=h>>>0,!O){const Pe=Math.pow(2,8*v-1);k(this,l,h,v,Pe-1,-Pe)}let F=0,z=1,ce=0;for(this[h]=l&255;++F<v&&(z*=256);)l<0&&ce===0&&this[h+F-1]!==0&&(ce=1),this[h+F]=(l/z>>0)-ce&255;return h+v},a.prototype.writeIntBE=function(l,h,v,O){if(l=+l,h=h>>>0,!O){const Pe=Math.pow(2,8*v-1);k(this,l,h,v,Pe-1,-Pe)}let F=v-1,z=1,ce=0;for(this[h+F]=l&255;--F>=0&&(z*=256);)l<0&&ce===0&&this[h+F+1]!==0&&(ce=1),this[h+F]=(l/z>>0)-ce&255;return h+v},a.prototype.writeInt8=function(l,h,v){return l=+l,h=h>>>0,v||k(this,l,h,1,127,-128),l<0&&(l=255+l+1),this[h]=l&255,h+1},a.prototype.writeInt16LE=function(l,h,v){return l=+l,h=h>>>0,v||k(this,l,h,2,32767,-32768),this[h]=l&255,this[h+1]=l>>>8,h+2},a.prototype.writeInt16BE=function(l,h,v){return l=+l,h=h>>>0,v||k(this,l,h,2,32767,-32768),this[h]=l>>>8,this[h+1]=l&255,h+2},a.prototype.writeInt32LE=function(l,h,v){return l=+l,h=h>>>0,v||k(this,l,h,4,2147483647,-2147483648),this[h]=l&255,this[h+1]=l>>>8,this[h+2]=l>>>16,this[h+3]=l>>>24,h+4},a.prototype.writeInt32BE=function(l,h,v){return l=+l,h=h>>>0,v||k(this,l,h,4,2147483647,-2147483648),l<0&&(l=4294967295+l+1),this[h]=l>>>24,this[h+1]=l>>>16,this[h+2]=l>>>8,this[h+3]=l&255,h+4},a.prototype.writeBigInt64LE=yr(function(l,h=0){return N(this,l,h,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=yr(function(l,h=0){return H(this,l,h,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Z(m,l,h,v,O,F){if(h+v>m.length)throw new RangeError("Index out of range");if(h<0)throw new RangeError("Index out of range")}function Q(m,l,h,v,O){return l=+l,h=h>>>0,O||Z(m,l,h,4),r.write(m,l,h,v,23,4),h+4}a.prototype.writeFloatLE=function(l,h,v){return Q(this,l,h,!0,v)},a.prototype.writeFloatBE=function(l,h,v){return Q(this,l,h,!1,v)};function ie(m,l,h,v,O){return l=+l,h=h>>>0,O||Z(m,l,h,8),r.write(m,l,h,v,52,8),h+8}a.prototype.writeDoubleLE=function(l,h,v){return ie(this,l,h,!0,v)},a.prototype.writeDoubleBE=function(l,h,v){return ie(this,l,h,!1,v)},a.prototype.copy=function(l,h,v,O){if(!a.isBuffer(l))throw new TypeError("argument should be a Buffer");if(v||(v=0),!O&&O!==0&&(O=this.length),h>=l.length&&(h=l.length),h||(h=0),O>0&&O<v&&(O=v),O===v||l.length===0||this.length===0)return 0;if(h<0)throw new RangeError("targetStart out of bounds");if(v<0||v>=this.length)throw new RangeError("Index out of range");if(O<0)throw new RangeError("sourceEnd out of bounds");O>this.length&&(O=this.length),l.length-h<O-v&&(O=l.length-h+v);const F=O-v;return this===l&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(h,v,O):Uint8Array.prototype.set.call(l,this.subarray(v,O),h),F},a.prototype.fill=function(l,h,v,O){if(typeof l=="string"){if(typeof h=="string"?(O=h,h=0,v=this.length):typeof v=="string"&&(O=v,v=this.length),O!==void 0&&typeof O!="string")throw new TypeError("encoding must be a string");if(typeof O=="string"&&!a.isEncoding(O))throw new TypeError("Unknown encoding: "+O);if(l.length===1){const z=l.charCodeAt(0);(O==="utf8"&&z<128||O==="latin1")&&(l=z)}}else typeof l=="number"?l=l&255:typeof l=="boolean"&&(l=Number(l));if(h<0||this.length<h||this.length<v)throw new RangeError("Out of range index");if(v<=h)return this;h=h>>>0,v=v===void 0?this.length:v>>>0,l||(l=0);let F;if(typeof l=="number")for(F=h;F<v;++F)this[F]=l;else{const z=a.isBuffer(l)?l:a.from(l,O),ce=z.length;if(ce===0)throw new TypeError('The value "'+l+'" is invalid for argument "value"');for(F=0;F<v-h;++F)this[F+h]=z[F%ce]}return this};const ne={};function re(m,l,h){ne[m]=class extends h{constructor(){super(),Object.defineProperty(this,"message",{value:l.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${m}]`,this.stack,delete this.name}get code(){return m}set code(O){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:O,writable:!0})}toString(){return`${this.name} [${m}]: ${this.message}`}}}re("ERR_BUFFER_OUT_OF_BOUNDS",function(m){return m?`${m} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),re("ERR_INVALID_ARG_TYPE",function(m,l){return`The "${m}" argument must be of type number. Received type ${typeof l}`},TypeError),re("ERR_OUT_OF_RANGE",function(m,l,h){let v=`The value of "${m}" is out of range.`,O=h;return Number.isInteger(h)&&Math.abs(h)>2**32?O=te(String(h)):typeof h=="bigint"&&(O=String(h),(h>BigInt(2)**BigInt(32)||h<-(BigInt(2)**BigInt(32)))&&(O=te(O)),O+="n"),v+=` It must be ${l}. Received ${O}`,v},RangeError);function te(m){let l="",h=m.length;const v=m[0]==="-"?1:0;for(;h>=v+4;h-=3)l=`_${m.slice(h-3,h)}${l}`;return`${m.slice(0,h)}${l}`}function se(m,l,h){he(l,"offset"),(m[l]===void 0||m[l+h]===void 0)&&Ae(l,m.length-(h+1))}function de(m,l,h,v,O,F){if(m>h||m<l){const z=typeof l=="bigint"?"n":"";let ce;throw l===0||l===BigInt(0)?ce=`>= 0${z} and < 2${z} ** ${(F+1)*8}${z}`:ce=`>= -(2${z} ** ${(F+1)*8-1}${z}) and < 2 ** ${(F+1)*8-1}${z}`,new ne.ERR_OUT_OF_RANGE("value",ce,m)}se(v,O,F)}function he(m,l){if(typeof m!="number")throw new ne.ERR_INVALID_ARG_TYPE(l,"number",m)}function Ae(m,l,h){throw Math.floor(m)!==m?(he(m,h),new ne.ERR_OUT_OF_RANGE("offset","an integer",m)):l<0?new ne.ERR_BUFFER_OUT_OF_BOUNDS:new ne.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${l}`,m)}const ot=/[^+/0-9A-Za-z-_]/g;function Re(m){if(m=m.split("=")[0],m=m.trim().replace(ot,""),m.length<2)return"";for(;m.length%4!==0;)m=m+"=";return m}function Rt(m,l){l=l||1/0;let h;const v=m.length;let O=null;const F=[];for(let z=0;z<v;++z){if(h=m.charCodeAt(z),h>55295&&h<57344){if(!O){if(h>56319){(l-=3)>-1&&F.push(239,191,189);continue}else if(z+1===v){(l-=3)>-1&&F.push(239,191,189);continue}O=h;continue}if(h<56320){(l-=3)>-1&&F.push(239,191,189),O=h;continue}h=(O-55296<<10|h-56320)+65536}else O&&(l-=3)>-1&&F.push(239,191,189);if(O=null,h<128){if((l-=1)<0)break;F.push(h)}else if(h<2048){if((l-=2)<0)break;F.push(h>>6|192,h&63|128)}else if(h<65536){if((l-=3)<0)break;F.push(h>>12|224,h>>6&63|128,h&63|128)}else if(h<1114112){if((l-=4)<0)break;F.push(h>>18|240,h>>12&63|128,h>>6&63|128,h&63|128)}else throw new Error("Invalid code point")}return F}function Fr(m){const l=[];for(let h=0;h<m.length;++h)l.push(m.charCodeAt(h)&255);return l}function G(m,l){let h,v,O;const F=[];for(let z=0;z<m.length&&!((l-=2)<0);++z)h=m.charCodeAt(z),v=h>>8,O=h%256,F.push(O),F.push(v);return F}function Nt(m){return t.toByteArray(Re(m))}function Ge(m,l,h,v){let O;for(O=0;O<v&&!(O+h>=l.length||O>=m.length);++O)l[O+h]=m[O];return O}function Ve(m,l){return m instanceof l||m!=null&&m.constructor!=null&&m.constructor.name!=null&&m.constructor.name===l.name}function hr(m){return m!==m}const ln=function(){const m="0123456789abcdef",l=new Array(256);for(let h=0;h<16;++h){const v=h*16;for(let O=0;O<16;++O)l[v+O]=m[h]+m[O]}return l}();function yr(m){return typeof BigInt>"u"?Ly:m}function Ly(){throw new Error("BigInt not supported")}})(un);var Yi={Array:function(e){return e!=null&&e.constructor===Array},Boolean:function(e){return typeof e=="boolean"},Function:function(e){return typeof e=="function"},Nil:function(e){return e==null},Number:function(e){return typeof e=="number"},Object:function(e){return typeof e=="object"},String:function(e){return typeof e=="string"},"":function(){return!0}};Yi.Null=Yi.Nil;for(var vd in Yi)Yi[vd].toJSON=(function(e){return e}).bind(null,vd);var rf=Yi,qr=rf;function $0(e){return e.name||e.toString().match(/function (.*?)\s*\(/)[1]}function nf(e){return qr.Nil(e)?"":$0(e.constructor)}function mE(e){return qr.Function(e)?"":qr.String(e)?JSON.stringify(e):e&&qr.Object(e)?"":e}function sf(e,t){Error.captureStackTrace&&Error.captureStackTrace(e,t)}function Ys(e){return qr.Function(e)?e.toJSON?e.toJSON():$0(e):qr.Array(e)?"Array":e&&qr.Object(e)?"Object":e!==void 0?e:""}function U0(e,t,r){var n=mE(t);return"Expected "+Ys(e)+", got"+(r!==""?" "+r:"")+(n!==""?" "+n:"")}function fr(e,t,r){r=r||nf(t),this.message=U0(e,t,r),sf(this,fr),this.__type=e,this.__value=t,this.__valueTypeName=r}fr.prototype=Object.create(Error.prototype);fr.prototype.constructor=fr;function gE(e,t,r,n,i){var s='" of type ';return t==="key"&&(s='" with key type '),U0('property "'+Ys(r)+s+Ys(e),n,i)}function kn(e,t,r,n,i){e?(i=i||nf(n),this.message=gE(e,r,t,n,i)):this.message='Unexpected property "'+t+'"',sf(this,fr),this.__label=r,this.__property=t,this.__type=e,this.__value=n,this.__valueTypeName=i}kn.prototype=Object.create(Error.prototype);kn.prototype.constructor=fr;function bE(e,t){return new fr(e,{},t)}function wE(e,t,r){return e instanceof kn?(t=t+"."+e.__property,e=new kn(e.__type,t,e.__label,e.__value,e.__valueTypeName)):e instanceof fr&&(e=new kn(e.__type,t,r,e.__value,e.__valueTypeName)),sf(e),e}var H0={TfTypeError:fr,TfPropertyTypeError:kn,tfCustomError:bE,tfSubError:wE,tfJSON:Ys,getValueTypeName:nf},ia,Ed;function vE(){if(Ed)return ia;Ed=1;var e=rf,t=H0;function r(I){return Buffer.isBuffer(I)}function n(I){return typeof I=="string"&&/^([0-9a-f]{2})+$/i.test(I)}function i(I,R){var L=I.toJSON();function S($){if(!I($))return!1;if($.length===R)return!0;throw t.tfCustomError(L+"(Length: "+R+")",L+"(Length: "+$.length+")")}return S.toJSON=function(){return L},S}var s=i.bind(null,e.Array),o=i.bind(null,r),a=i.bind(null,n),c=i.bind(null,e.String);function f(I,R,L){L=L||e.Number;function S($,C){return L($,C)&&$>I&&$<R}return S.toJSON=function(){return`${L.toJSON()} between [${I}, ${R}]`},S}var u=Math.pow(2,53)-1;function d(I){return typeof I=="number"&&isFinite(I)}function y(I){return I<<24>>24===I}function p(I){return I<<16>>16===I}function g(I){return(I|0)===I}function b(I){return typeof I=="number"&&I>=-u&&I<=u&&Math.floor(I)===I}function E(I){return(I&255)===I}function A(I){return(I&65535)===I}function P(I){return I>>>0===I}function w(I){return typeof I=="number"&&I>=0&&I<=u&&Math.floor(I)===I}var _={ArrayN:s,Buffer:r,BufferN:o,Finite:d,Hex:n,HexN:a,Int8:y,Int16:p,Int32:g,Int53:b,Range:f,StringN:c,UInt8:E,UInt16:A,UInt32:P,UInt53:w};for(var T in _)_[T].toJSON=(function(I){return I}).bind(null,T);return ia=_,ia}var us=H0,He=rf,Jt=us.tfJSON,L0=us.TfTypeError,M0=us.TfPropertyTypeError,ii=us.tfSubError,EE=us.getValueTypeName,ir={arrayOf:function(t,r){t=zt(t),r=r||{};function n(i,s){return!He.Array(i)||He.Nil(i)||r.minLength!==void 0&&i.length<r.minLength||r.maxLength!==void 0&&i.length>r.maxLength||r.length!==void 0&&i.length!==r.length?!1:i.every(function(o,a){try{return Xe(t,o,s)}catch(c){throw ii(c,a)}})}return n.toJSON=function(){var i="["+Jt(t)+"]";return r.length!==void 0?i+="{"+r.length+"}":(r.minLength!==void 0||r.maxLength!==void 0)&&(i+="{"+(r.minLength===void 0?0:r.minLength)+","+(r.maxLength===void 0?1/0:r.maxLength)+"}"),i},n},maybe:function e(t){t=zt(t);function r(n,i){return He.Nil(n)||t(n,i,e)}return r.toJSON=function(){return"?"+Jt(t)},r},map:function(t,r){t=zt(t),r&&(r=zt(r));function n(i,s){if(!He.Object(i)||He.Nil(i))return!1;for(var o in i){try{r&&Xe(r,o,s)}catch(c){throw ii(c,o,"key")}try{var a=i[o];Xe(t,a,s)}catch(c){throw ii(c,o)}}return!0}return r?n.toJSON=function(){return"{"+Jt(r)+": "+Jt(t)+"}"}:n.toJSON=function(){return"{"+Jt(t)+"}"},n},object:function(t){var r={};for(var n in t)r[n]=zt(t[n]);function i(s,o){if(!He.Object(s)||He.Nil(s))return!1;var a;try{for(a in r){var c=r[a],f=s[a];Xe(c,f,o)}}catch(u){throw ii(u,a)}if(o){for(a in s)if(!r[a])throw new M0(void 0,a)}return!0}return i.toJSON=function(){return Jt(r)},i},anyOf:function(){var t=[].slice.call(arguments).map(zt);function r(n,i){return t.some(function(s){try{return Xe(s,n,i)}catch{return!1}})}return r.toJSON=function(){return t.map(Jt).join("|")},r},allOf:function(){var t=[].slice.call(arguments).map(zt);function r(n,i){return t.every(function(s){try{return Xe(s,n,i)}catch{return!1}})}return r.toJSON=function(){return t.map(Jt).join(" & ")},r},quacksLike:function(t){function r(n){return t===EE(n)}return r.toJSON=function(){return t},r},tuple:function(){var t=[].slice.call(arguments).map(zt);function r(n,i){return He.Nil(n)||He.Nil(n.length)||i&&n.length!==t.length?!1:t.every(function(s,o){try{return Xe(s,n[o],i)}catch(a){throw ii(a,o)}})}return r.toJSON=function(){return"("+t.map(Jt).join(", ")+")"},r},value:function(t){function r(n){return n===t}return r.toJSON=function(){return t},r}};ir.oneOf=ir.anyOf;function zt(e){if(He.String(e))return e[0]==="?"?ir.maybe(e.slice(1)):He[e]||ir.quacksLike(e);if(e&&He.Object(e)){if(He.Array(e)){if(e.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return ir.arrayOf(e[0])}return ir.object(e)}else if(He.Function(e))return e;return ir.value(e)}function Xe(e,t,r,n){if(He.Function(e)){if(e(t,r))return!0;throw new L0(n||e,t)}return Xe(zt(e),t,r)}for(var Ir in He)Xe[Ir]=He[Ir];for(Ir in ir)Xe[Ir]=ir[Ir];var xd=vE();for(Ir in xd)Xe[Ir]=xd[Ir];Xe.compile=zt;Xe.TfTypeError=L0;Xe.TfPropertyTypeError=M0;var xE=Xe;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.oneOf=e.Null=e.BufferN=e.Function=e.UInt32=e.UInt8=e.tuple=e.maybe=e.Hex=e.Buffer=e.String=e.Boolean=e.Array=e.Number=e.Hash256bit=e.Hash160bit=e.Buffer256bit=e.isTaptree=e.isTapleaf=e.TAPLEAF_VERSION_MASK=e.Satoshi=e.isPoint=e.stacksEqual=e.typeforce=void 0;const t=un;e.typeforce=xE;const r=t.Buffer.alloc(32,0),n=t.Buffer.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex");function i(u,d){return u.length!==d.length?!1:u.every((y,p)=>y.equals(d[p]))}e.stacksEqual=i;function s(u){if(!t.Buffer.isBuffer(u)||u.length<33)return!1;const d=u[0],y=u.slice(1,33);if(y.compare(r)===0||y.compare(n)>=0)return!1;if((d===2||d===3)&&u.length===33)return!0;const p=u.slice(33);return p.compare(r)===0||p.compare(n)>=0?!1:d===4&&u.length===65}e.isPoint=s;const o=21*1e14;function a(u){return e.typeforce.UInt53(u)&&u<=o}e.Satoshi=a,e.TAPLEAF_VERSION_MASK=254;function c(u){return!u||!("output"in u)||!t.Buffer.isBuffer(u.output)?!1:u.version!==void 0?(u.version&e.TAPLEAF_VERSION_MASK)===u.version:!0}e.isTapleaf=c;function f(u){return(0,e.Array)(u)?u.length!==2?!1:u.every(d=>f(d)):c(u)}e.isTaptree=f,e.Buffer256bit=e.typeforce.BufferN(32),e.Hash160bit=e.typeforce.BufferN(20),e.Hash256bit=e.typeforce.BufferN(32),e.Number=e.typeforce.Number,e.Array=e.typeforce.Array,e.Boolean=e.typeforce.Boolean,e.String=e.typeforce.String,e.Buffer=e.typeforce.Buffer,e.Hex=e.typeforce.Hex,e.maybe=e.typeforce.maybe,e.tuple=e.typeforce.tuple,e.UInt8=e.typeforce.UInt8,e.UInt32=e.typeforce.UInt32,e.Function=e.typeforce.Function,e.BufferN=e.typeforce.BufferN,e.Null=e.typeforce.Null,e.oneOf=e.typeforce.oneOf})(qe);var fs={},Le={};Object.defineProperty(Le,"__esModule",{value:!0});Le.BufferReader=Le.BufferWriter=Le.cloneBuffer=Le.reverseBuffer=Le.writeUInt64LE=Le.readUInt64LE=Le.varuint=void 0;const Gr=qe,{typeforce:D0}=Gr,Zi=Kl;Le.varuint=Zi;function j0(e,t){if(typeof e!="number")throw new Error("cannot write a non-number as a number");if(e<0)throw new Error("specified a negative value for writing an unsigned value");if(e>t)throw new Error("RangeError: value out of range");if(Math.floor(e)!==e)throw new Error("value has a fractional component")}function z0(e,t){const r=e.readUInt32LE(t);let n=e.readUInt32LE(t+4);return n*=4294967296,j0(n+r,9007199254740991),n+r}Le.readUInt64LE=z0;function q0(e,t,r){return j0(t,9007199254740991),e.writeInt32LE(t&-1,r),e.writeUInt32LE(Math.floor(t/4294967296),r+4),r+8}Le.writeUInt64LE=q0;function AE(e){if(e.length<1)return e;let t=e.length-1,r=0;for(let n=0;n<e.length/2;n++)r=e[n],e[n]=e[t],e[t]=r,t--;return e}Le.reverseBuffer=AE;function _E(e){const t=Buffer.allocUnsafe(e.length);return e.copy(t),t}Le.cloneBuffer=_E;class of{static withCapacity(t){return new of(Buffer.alloc(t))}constructor(t,r=0){this.buffer=t,this.offset=r,D0(Gr.tuple(Gr.Buffer,Gr.UInt32),[t,r])}writeUInt8(t){this.offset=this.buffer.writeUInt8(t,this.offset)}writeInt32(t){this.offset=this.buffer.writeInt32LE(t,this.offset)}writeUInt32(t){this.offset=this.buffer.writeUInt32LE(t,this.offset)}writeUInt64(t){this.offset=q0(this.buffer,t,this.offset)}writeVarInt(t){Zi.encode(t,this.buffer,this.offset),this.offset+=Zi.encode.bytes}writeSlice(t){if(this.buffer.length<this.offset+t.length)throw new Error("Cannot write slice out of bounds");this.offset+=t.copy(this.buffer,this.offset)}writeVarSlice(t){this.writeVarInt(t.length),this.writeSlice(t)}writeVector(t){this.writeVarInt(t.length),t.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}`)}}Le.BufferWriter=of;class SE{constructor(t,r=0){this.buffer=t,this.offset=r,D0(Gr.tuple(Gr.Buffer,Gr.UInt32),[t,r])}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=z0(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const t=Zi.decode(this.buffer,this.offset);return this.offset+=Zi.decode.bytes,t}readSlice(t){if(this.buffer.length<this.offset+t)throw new Error("Cannot read slice out of bounds");const r=this.buffer.slice(this.offset,this.offset+t);return this.offset+=t,r}readVarSlice(){return this.readSlice(this.readVarInt())}readVector(){const t=this.readVarInt(),r=[];for(let n=0;n<t;n++)r.push(this.readVarSlice());return r}}Le.BufferReader=SE;var Nr={};const PE=N0(e2);var Ln={},rt={},Qe={},af={},Po={};Object.defineProperty(Po,"__esModule",{value:!0});Po.crypto=void 0;Po.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;(function(e){/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */Object.defineProperty(e,"__esModule",{value:!0}),e.wrapXOFConstructorWithOpts=e.wrapConstructorWithOpts=e.wrapConstructor=e.Hash=e.nextTick=e.swap32IfBE=e.byteSwapIfBE=e.swap8IfBE=e.isLE=void 0,e.isBytes=r,e.anumber=n,e.abytes=i,e.ahash=s,e.aexists=o,e.aoutput=a,e.u8=c,e.u32=f,e.clean=u,e.createView=d,e.rotr=y,e.rotl=p,e.byteSwap=g,e.byteSwap32=b,e.bytesToHex=P,e.hexToBytes=T,e.asyncLoop=R,e.utf8ToBytes=L,e.bytesToUtf8=S,e.toBytes=$,e.kdfInputToBytes=C,e.concatBytes=U,e.checkOpts=j,e.createHasher=Y,e.createOptHasher=X,e.createXOFer=J,e.randomBytes=M;const t=Po;function r(B){return B instanceof Uint8Array||ArrayBuffer.isView(B)&&B.constructor.name==="Uint8Array"}function n(B){if(!Number.isSafeInteger(B)||B<0)throw new Error("positive integer expected, got "+B)}function i(B,...q){if(!r(B))throw new Error("Uint8Array expected");if(q.length>0&&!q.includes(B.length))throw new Error("Uint8Array expected of length "+q+", got length="+B.length)}function s(B){if(typeof B!="function"||typeof B.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");n(B.outputLen),n(B.blockLen)}function o(B,q=!0){if(B.destroyed)throw new Error("Hash instance has been destroyed");if(q&&B.finished)throw new Error("Hash#digest() has already been called")}function a(B,q){i(B);const W=q.outputLen;if(B.length<W)throw new Error("digestInto() expects output buffer of length at least "+W)}function c(B){return new Uint8Array(B.buffer,B.byteOffset,B.byteLength)}function f(B){return new Uint32Array(B.buffer,B.byteOffset,Math.floor(B.byteLength/4))}function u(...B){for(let q=0;q<B.length;q++)B[q].fill(0)}function d(B){return new DataView(B.buffer,B.byteOffset,B.byteLength)}function y(B,q){return B<<32-q|B>>>q}function p(B,q){return B<<q|B>>>32-q>>>0}e.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function g(B){return B<<24&4278190080|B<<8&16711680|B>>>8&65280|B>>>24&255}e.swap8IfBE=e.isLE?B=>B:B=>g(B),e.byteSwapIfBE=e.swap8IfBE;function b(B){for(let q=0;q<B.length;q++)B[q]=g(B[q]);return B}e.swap32IfBE=e.isLE?B=>B:b;const E=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",A=Array.from({length:256},(B,q)=>q.toString(16).padStart(2,"0"));function P(B){if(i(B),E)return B.toHex();let q="";for(let W=0;W<B.length;W++)q+=A[B[W]];return q}const w={_0:48,_9:57,A:65,F:70,a:97,f:102};function _(B){if(B>=w._0&&B<=w._9)return B-w._0;if(B>=w.A&&B<=w.F)return B-(w.A-10);if(B>=w.a&&B<=w.f)return B-(w.a-10)}function T(B){if(typeof B!="string")throw new Error("hex string expected, got "+typeof B);if(E)return Uint8Array.fromHex(B);const q=B.length,W=q/2;if(q%2)throw new Error("hex string expected, got unpadded hex of length "+q);const k=new Uint8Array(W);for(let N=0,H=0;N<W;N++,H+=2){const Z=_(B.charCodeAt(H)),Q=_(B.charCodeAt(H+1));if(Z===void 0||Q===void 0){const ie=B[H]+B[H+1];throw new Error('hex string expected, got non-hex character "'+ie+'" at index '+H)}k[N]=Z*16+Q}return k}const I=async()=>{};e.nextTick=I;async function R(B,q,W){let k=Date.now();for(let N=0;N<B;N++){W(N);const H=Date.now()-k;H>=0&&H<q||(await(0,e.nextTick)(),k+=H)}}function L(B){if(typeof B!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(B))}function S(B){return new TextDecoder().decode(B)}function $(B){return typeof B=="string"&&(B=L(B)),i(B),B}function C(B){return typeof B=="string"&&(B=L(B)),i(B),B}function U(...B){let q=0;for(let k=0;k<B.length;k++){const N=B[k];i(N),q+=N.length}const W=new Uint8Array(q);for(let k=0,N=0;k<B.length;k++){const H=B[k];W.set(H,N),N+=H.length}return W}function j(B,q){if(q!==void 0&&{}.toString.call(q)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(B,q)}class V{}e.Hash=V;function Y(B){const q=k=>B().update($(k)).digest(),W=B();return q.outputLen=W.outputLen,q.blockLen=W.blockLen,q.create=()=>B(),q}function X(B){const q=(k,N)=>B(N).update($(k)).digest(),W=B({});return q.outputLen=W.outputLen,q.blockLen=W.blockLen,q.create=k=>B(k),q}function J(B){const q=(k,N)=>B(N).update($(k)).digest(),W=B({});return q.outputLen=W.outputLen,q.blockLen=W.blockLen,q.create=k=>B(k),q}e.wrapConstructor=Y,e.wrapConstructorWithOpts=X,e.wrapXOFConstructorWithOpts=J;function M(B=32){if(t.crypto&&typeof t.crypto.getRandomValues=="function")return t.crypto.getRandomValues(new Uint8Array(B));if(t.crypto&&typeof t.crypto.randomBytes=="function")return Uint8Array.from(t.crypto.randomBytes(B));throw new Error("crypto.getRandomValues must be defined")}})(af);Object.defineProperty(Qe,"__esModule",{value:!0});Qe.SHA512_IV=Qe.SHA384_IV=Qe.SHA224_IV=Qe.SHA256_IV=Qe.HashMD=void 0;Qe.setBigUint64=G0;Qe.Chi=TE;Qe.Maj=IE;const Ut=af;function G0(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),c=n?4:0,f=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+f,a,n)}function TE(e,t,r){return e&t^~e&r}function IE(e,t,r){return e&t^e&r^t&r}class kE extends Ut.Hash{constructor(t,r,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(t),this.view=(0,Ut.createView)(this.buffer)}update(t){(0,Ut.aexists)(this),t=(0,Ut.toBytes)(t),(0,Ut.abytes)(t);const{view:r,buffer:n,blockLen:i}=this,s=t.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=(0,Ut.createView)(t);for(;i<=s-o;o+=i)this.process(c,o);continue}n.set(t.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){(0,Ut.aexists)(this),(0,Ut.aoutput)(t,this),this.finished=!0;const{buffer:r,view:n,blockLen:i,isLE:s}=this;let{pos:o}=this;r[o++]=128,(0,Ut.clean)(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(n,0),o=0);for(let d=o;d<i;d++)r[d]=0;G0(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=(0,Ut.createView)(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const f=c/4,u=this.get();if(f>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<f;d++)a.setUint32(4*d,u[d],s)}digest(){const{buffer:t,outputLen:r}=this;this.digestInto(t);const n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:r,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return t.destroyed=o,t.finished=s,t.length=i,t.pos=a,i%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}}Qe.HashMD=kE;Qe.SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);Qe.SHA224_IV=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);Qe.SHA384_IV=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]);Qe.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 Vr=Qe,Me=af,bn=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),wr=new Uint32Array(80);class V0 extends Vr.HashMD{constructor(){super(64,20,8,!1),this.A=bn[0]|0,this.B=bn[1]|0,this.C=bn[2]|0,this.D=bn[3]|0,this.E=bn[4]|0}get(){const{A:t,B:r,C:n,D:i,E:s}=this;return[t,r,n,i,s]}set(t,r,n,i,s){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0}process(t,r){for(let c=0;c<16;c++,r+=4)wr[c]=t.getUint32(r,!1);for(let c=16;c<80;c++)wr[c]=(0,Me.rotl)(wr[c-3]^wr[c-8]^wr[c-14]^wr[c-16],1);let{A:n,B:i,C:s,D:o,E:a}=this;for(let c=0;c<80;c++){let f,u;c<20?(f=(0,Vr.Chi)(i,s,o),u=1518500249):c<40?(f=i^s^o,u=1859775393):c<60?(f=(0,Vr.Maj)(i,s,o),u=2400959708):(f=i^s^o,u=3395469782);const d=(0,Me.rotl)(n,5)+f+a+u+wr[c]|0;a=o,o=s,s=(0,Me.rotl)(i,30),i=n,n=d}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,this.set(n,i,s,o,a)}roundClean(){(0,Me.clean)(wr)}destroy(){this.set(0,0,0,0,0),(0,Me.clean)(this.buffer)}}rt.SHA1=V0;rt.sha1=(0,Me.createHasher)(()=>new V0);const BE=Math.pow(2,32),OE=Array.from({length:64},(e,t)=>Math.floor(BE*Math.abs(Math.sin(t+1)))),_s=bn.slice(0,4),sa=new Uint32Array(16);class W0 extends Vr.HashMD{constructor(){super(64,16,8,!0),this.A=_s[0]|0,this.B=_s[1]|0,this.C=_s[2]|0,this.D=_s[3]|0}get(){const{A:t,B:r,C:n,D:i}=this;return[t,r,n,i]}set(t,r,n,i){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0}process(t,r){for(let a=0;a<16;a++,r+=4)sa[a]=t.getUint32(r,!0);let{A:n,B:i,C:s,D:o}=this;for(let a=0;a<64;a++){let c,f,u;a<16?(c=(0,Vr.Chi)(i,s,o),f=a,u=[7,12,17,22]):a<32?(c=(0,Vr.Chi)(o,i,s),f=(5*a+1)%16,u=[5,9,14,20]):a<48?(c=i^s^o,f=(3*a+5)%16,u=[4,11,16,23]):(c=s^(i|~o),f=7*a%16,u=[6,10,15,21]),c=c+n+OE[a]+sa[f],n=o,o=s,s=i,i=i+(0,Me.rotl)(c,u[a%4])}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,this.set(n,i,s,o)}roundClean(){(0,Me.clean)(sa)}destroy(){this.set(0,0,0,0),(0,Me.clean)(this.buffer)}}rt.MD5=W0;rt.md5=(0,Me.createHasher)(()=>new W0);const CE=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),K0=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),RE=K0.map(e=>(9*e+5)%16),Y0=(()=>{const r=[[K0],[RE]];for(let n=0;n<4;n++)for(let i of r)i.push(i[n].map(s=>CE[s]));return r})(),Z0=Y0[0],X0=Y0[1],J0=[[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(e=>Uint8Array.from(e)),NE=Z0.map((e,t)=>e.map(r=>J0[t][r])),FE=X0.map((e,t)=>e.map(r=>J0[t][r])),$E=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),UE=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function Ad(e,t,r,n){return e===0?t^r^n:e===1?t&r|~t&n:e===2?(t|~r)^n:e===3?t&n|r&~n:t^(r|~n)}const Ss=new Uint32Array(16);class Q0 extends Vr.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:t,h1:r,h2:n,h3:i,h4:s}=this;return[t,r,n,i,s]}set(t,r,n,i,s){this.h0=t|0,this.h1=r|0,this.h2=n|0,this.h3=i|0,this.h4=s|0}process(t,r){for(let p=0;p<16;p++,r+=4)Ss[p]=t.getUint32(r,!0);let n=this.h0|0,i=n,s=this.h1|0,o=s,a=this.h2|0,c=a,f=this.h3|0,u=f,d=this.h4|0,y=d;for(let p=0;p<5;p++){const g=4-p,b=$E[p],E=UE[p],A=Z0[p],P=X0[p],w=NE[p],_=FE[p];for(let T=0;T<16;T++){const I=(0,Me.rotl)(n+Ad(p,s,a,f)+Ss[A[T]]+b,w[T])+d|0;n=d,d=f,f=(0,Me.rotl)(a,10)|0,a=s,s=I}for(let T=0;T<16;T++){const I=(0,Me.rotl)(i+Ad(g,o,c,u)+Ss[P[T]]+E,_[T])+y|0;i=y,y=u,u=(0,Me.rotl)(c,10)|0,c=o,o=I}}this.set(this.h1+a+u|0,this.h2+f+y|0,this.h3+d+i|0,this.h4+n+o|0,this.h0+s+c|0)}roundClean(){(0,Me.clean)(Ss)}destroy(){this.destroyed=!0,(0,Me.clean)(this.buffer),this.set(0,0,0,0,0)}}rt.RIPEMD160=Q0;rt.ripemd160=(0,Me.createHasher)(()=>new Q0);Object.defineProperty(Ln,"__esModule",{value:!0});Ln.sha1=Ln.SHA1=void 0;const ey=rt;Ln.SHA1=ey.SHA1;Ln.sha1=ey.sha1;const ty=N0(Mb);(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.taggedHash=e.TAGGED_HASH_PREFIXES=e.TAGS=e.hash256=e.hash160=e.sha256=e.sha1=e.ripemd160=void 0;const t=PE,r=Ln,n=ty;function i(u){return Buffer.from((0,t.ripemd160)(Uint8Array.from(u)))}e.ripemd160=i;function s(u){return Buffer.from((0,r.sha1)(Uint8Array.from(u)))}e.sha1=s;function o(u){return Buffer.from((0,n.sha256)(Uint8Array.from(u)))}e.sha256=o;function a(u){return Buffer.from((0,t.ripemd160)((0,n.sha256)(Uint8Array.from(u))))}e.hash160=a;function c(u){return Buffer.from((0,n.sha256)((0,n.sha256)(Uint8Array.from(u))))}e.hash256=c,e.TAGS=["BIP0340/challenge","BIP0340/aux","BIP0340/nonce","TapLeaf","TapBranch","TapSighash","TapTweak","KeyAgg list","KeyAgg coefficient"],e.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 f(u,d){return o(Buffer.concat([e.TAGGED_HASH_PREFIXES[u],d]))}e.taggedHash=f})(Nr);var oa={},ar={};Object.defineProperty(ar,"__esModule",{value:!0});ar.encode=ar.decode=ar.check=void 0;function HE(e){if(e.length<8||e.length>72||e[0]!==48||e[1]!==e.length-2||e[2]!==2)return!1;const t=e[3];if(t===0||5+t>=e.length||e[4+t]!==2)return!1;const r=e[5+t];return!(r===0||6+t+r!==e.length||e[4]&128||t>1&&e[4]===0&&!(e[5]&128)||e[t+6]&128||r>1&&e[t+6]===0&&!(e[t+7]&128))}ar.check=HE;function LE(e){if(e.length<8)throw new Error("DER sequence length is too short");if(e.length>72)throw new Error("DER sequence length is too long");if(e[0]!==48)throw new Error("Expected DER sequence");if(e[1]!==e.length-2)throw new Error("DER sequence length is invalid");if(e[2]!==2)throw new Error("Expected DER integer");const t=e[3];if(t===0)throw new Error("R length is zero");if(5+t>=e.length)throw new Error("R length is too long");if(e[4+t]!==2)throw new Error("Expected DER integer (2)");const r=e[5+t];if(r===0)throw new Error("S length is zero");if(6+t+r!==e.length)throw new Error("S length is invalid");if(e[4]&128)throw new Error("R value is negative");if(t>1&&e[4]===0&&!(e[5]&128))throw new Error("R value excessively padded");if(e[t+6]&128)throw new Error("S value is negative");if(r>1&&e[t+6]===0&&!(e[t+7]&128))throw new Error("S value excessively padded");return{r:e.slice(4,4+t),s:e.slice(6+t)}}ar.decode=LE;function ME(e,t){const r=e.length,n=t.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(e[0]&128)throw new Error("R value is negative");if(t[0]&128)throw new Error("S value is negative");if(r>1&&e[0]===0&&!(e[1]&128))throw new Error("R value excessively padded");if(n>1&&t[0]===0&&!(t[1]&128))throw new Error("S value excessively padded");const i=Buffer.allocUnsafe(6+r+n);return i[0]=48,i[1]=i.length-2,i[2]=2,i[3]=e.length,e.copy(i,4),i[4+r]=2,i[5+r]=t.length,t.copy(i,6+r),i}ar.encode=ME;var rn={};Object.defineProperty(rn,"__esModule",{value:!0});rn.REVERSE_OPS=rn.OPS=void 0;const iu={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};rn.OPS=iu;const ry={};rn.REVERSE_OPS=ry;for(const e of Object.keys(iu)){const t=iu[e];ry[t]=e}var kr={};Object.defineProperty(kr,"__esModule",{value:!0});kr.decode=kr.encode=kr.encodingLength=void 0;const Sr=rn;function ny(e){return e<Sr.OPS.OP_PUSHDATA1?1:e<=255?2:e<=65535?3:5}kr.encodingLength=ny;function DE(e,t,r){const n=ny(t);return n===1?e.writeUInt8(t,r):n===2?(e.writeUInt8(Sr.OPS.OP_PUSHDATA1,r),e.writeUInt8(t,r+1)):n===3?(e.writeUInt8(Sr.OPS.OP_PUSHDATA2,r),e.writeUInt16LE(t,r+1)):(e.writeUInt8(Sr.OPS.OP_PUSHDATA4,r),e.writeUInt32LE(t,r+1)),n}kr.encode=DE;function jE(e,t){const r=e.readUInt8(t);let n,i;if(r<Sr.OPS.OP_PUSHDATA1)n=r,i=1;else if(r===Sr.OPS.OP_PUSHDATA1){if(t+2>e.length)return null;n=e.readUInt8(t+1),i=2}else if(r===Sr.OPS.OP_PUSHDATA2){if(t+3>e.length)return null;n=e.readUInt16LE(t+1),i=3}else{if(t+5>e.length)return null;if(r!==Sr.OPS.OP_PUSHDATA4)throw new Error("Unexpected opcode");n=e.readUInt32LE(t+1),i=5}return{opcode:r,number:n,size:i}}kr.decode=jE;var Mn={};Object.defineProperty(Mn,"__esModule",{value:!0});Mn.encode=Mn.decode=void 0;function zE(e,t,r){t=t||4,r=r===void 0?!0:r;const n=e.length;if(n===0)return 0;if(n>t)throw new TypeError("Script number overflow");if(r&&!(e[n-1]&127)&&(n<=1||!(e[n-2]&128)))throw new Error("Non-minimally encoded script number");if(n===5){const s=e.readUInt32LE(0),o=e.readUInt8(4);return o&128?-((o&-129)*4294967296+s):o*4294967296+s}let i=0;for(let s=0;s<n;++s)i|=e[s]<<8*s;return e[n-1]&128?-(i&~(128<<8*(n-1))):i}Mn.decode=zE;function qE(e){return e>2147483647?5:e>8388607?4:e>32767?3:e>127?2:e>0?1:0}function GE(e){let t=Math.abs(e);const r=qE(t),n=Buffer.allocUnsafe(r),i=e<0;for(let s=0;s<r;++s)n.writeUInt8(t&255,s),t>>=8;return n[r-1]&128?n.writeUInt8(i?128:0,r-1):i&&(n[r-1]|=128),n}Mn.encode=GE;var $r={},_d;function VE(){if(_d)return $r;_d=1,Object.defineProperty($r,"__esModule",{value:!0}),$r.encode=$r.decode=void 0;const e=ar,t=lt(),r=qe,{typeforce:n}=r,i=Buffer.alloc(1,0);function s(f){let u=0;for(;f[u]===0;)++u;return u===f.length?i:(f=f.slice(u),f[0]&128?Buffer.concat([i,f],1+f.length):f)}function o(f){f[0]===0&&(f=f.slice(1));const u=Buffer.alloc(32,0),d=Math.max(0,32-f.length);return f.copy(u,d),u}function a(f){const u=f.readUInt8(f.length-1);if(!(0,t.isDefinedHashType)(u))throw new Error("Invalid hashType "+u);const d=e.decode(f.slice(0,-1)),y=o(d.r),p=o(d.s);return{signature:Buffer.concat([y,p],64),hashType:u}}$r.decode=a;function c(f,u){if(n({signature:r.BufferN(64),hashType:r.UInt8},{signature:f,hashType:u}),!(0,t.isDefinedHashType)(u))throw new Error("Invalid hashType "+u);const d=Buffer.allocUnsafe(1);d.writeUInt8(u,0);const y=s(f.slice(0,32)),p=s(f.slice(32,64));return Buffer.concat([e.encode(y,p),d])}return $r.encode=c,$r}var Sd;function lt(){return Sd||(Sd=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.signature=e.number=e.isCanonicalScriptSignature=e.isDefinedHashType=e.isCanonicalPubKey=e.toStack=e.fromASM=e.toASM=e.decompile=e.compile=e.countNonPushOnlyOPs=e.isPushOnly=e.OPS=void 0;const t=ar,r=rn;Object.defineProperty(e,"OPS",{enumerable:!0,get:function(){return r.OPS}});const n=kr,i=Mn,s=VE(),o=qe,{typeforce:a}=o,c=r.OPS.OP_RESERVED;function f(S){return o.Number(S)&&(S===r.OPS.OP_0||S>=r.OPS.OP_1&&S<=r.OPS.OP_16||S===r.OPS.OP_1NEGATE)}function u(S){return o.Buffer(S)||f(S)}function d(S){return o.Array(S)&&S.every(u)}e.isPushOnly=d;function y(S){return S.length-S.filter(u).length}e.countNonPushOnlyOPs=y;function p(S){if(S.length===0)return r.OPS.OP_0;if(S.length===1){if(S[0]>=1&&S[0]<=16)return c+S[0];if(S[0]===129)return r.OPS.OP_1NEGATE}}function g(S){return Buffer.isBuffer(S)}function b(S){return o.Array(S)}function E(S){return Buffer.isBuffer(S)}function A(S){if(g(S))return S;a(o.Array,S);const $=S.reduce((j,V)=>E(V)?V.length===1&&p(V)!==void 0?j+1:j+n.encodingLength(V.length)+V.length:j+1,0),C=Buffer.allocUnsafe($);let U=0;if(S.forEach(j=>{if(E(j)){const V=p(j);if(V!==void 0){C.writeUInt8(V,U),U+=1;return}U+=n.encode(C,j.length,U),j.copy(C,U),U+=j.length}else C.writeUInt8(j,U),U+=1}),U!==C.length)throw new Error("Could not decode chunks");return C}e.compile=A;function P(S){if(b(S))return S;a(o.Buffer,S);const $=[];let C=0;for(;C<S.length;){const U=S[C];if(U>r.OPS.OP_0&&U<=r.OPS.OP_PUSHDATA4){const j=n.decode(S,C);if(j===null||(C+=j.size,C+j.number>S.length))return null;const V=S.slice(C,C+j.number);C+=j.number;const Y=p(V);Y!==void 0?$.push(Y):$.push(V)}else $.push(U),C+=1}return $}e.decompile=P;function w(S){if(g(S)&&(S=P(S)),!S)throw new Error("Could not convert invalid chunks to ASM");return S.map($=>{if(E($)){const C=p($);if(C===void 0)return $.toString("hex");$=C}return r.REVERSE_OPS[$]}).join(" ")}e.toASM=w;function _(S){return a(o.String,S),A(S.split(" ").map($=>r.OPS[$]!==void 0?r.OPS[$]:(a(o.Hex,$),Buffer.from($,"hex"))))}e.fromASM=_;function T(S){return S=P(S),a(d,S),S.map($=>E($)?$:$===r.OPS.OP_0?Buffer.allocUnsafe(0):i.encode($-c))}e.toStack=T;function I(S){return o.isPoint(S)}e.isCanonicalPubKey=I;function R(S){const $=S&-129;return $>0&&$<4}e.isDefinedHashType=R;function L(S){return!Buffer.isBuffer(S)||!R(S[S.length-1])?!1:t.check(S.slice(0,-1))}e.isCanonicalScriptSignature=L,e.number=i,e.signature=s}(oa)),oa}Object.defineProperty(fs,"__esModule",{value:!0});fs.Transaction=void 0;const Be=Le,We=Nr,Pd=lt(),WE=lt(),ue=qe,{typeforce:Ht}=ue;function Dt(e){const t=e.length;return Be.varuint.encodingLength(t)+t}function KE(e){const t=e.length;return Be.varuint.encodingLength(t)+e.reduce((r,n)=>r+Dt(n),0)}const _r=Buffer.allocUnsafe(0),aa=[],ca=Buffer.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),Td=Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),YE=Buffer.from("ffffffffffffffff","hex"),ZE={script:_r,valueBuffer:YE};function XE(e){return e.value!==void 0}class ae{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(t,r){const n=new Be.BufferReader(t),i=new ae;i.version=n.readInt32();const s=n.readUInt8(),o=n.readUInt8();let a=!1;s===ae.ADVANCED_TRANSACTION_MARKER&&o===ae.ADVANCED_TRANSACTION_FLAG?a=!0:n.offset-=2;const c=n.readVarInt();for(let u=0;u<c;++u)i.ins.push({hash:n.readSlice(32),index:n.readUInt32(),script:n.readVarSlice(),sequence:n.readUInt32(),witness:aa});const f=n.readVarInt();for(let u=0;u<f;++u)i.outs.push({value:n.readUInt64(),script:n.readVarSlice()});if(a){for(let u=0;u<c;++u)i.ins[u].witness=n.readVector();if(!i.hasWitnesses())throw new Error("Transaction has superfluous witness data")}if(i.locktime=n.readUInt32(),r)return i;if(n.offset!==t.length)throw new Error("Transaction has unexpected data");return i}static fromHex(t){return ae.fromBuffer(Buffer.from(t,"hex"),!1)}static isCoinbaseHash(t){Ht(ue.Hash256bit,t);for(let r=0;r<32;++r)if(t[r]!==0)return!1;return!0}isCoinbase(){return this.ins.length===1&&ae.isCoinbaseHash(this.ins[0].hash)}addInput(t,r,n,i){return Ht(ue.tuple(ue.Hash256bit,ue.UInt32,ue.maybe(ue.UInt32),ue.maybe(ue.Buffer)),arguments),ue.Null(n)&&(n=ae.DEFAULT_SEQUENCE),this.ins.push({hash:t,index:r,script:i||_r,sequence:n,witness:aa})-1}addOutput(t,r){return Ht(ue.tuple(ue.Buffer,ue.Satoshi),arguments),this.outs.push({script:t,value:r})-1}hasWitnesses(){return this.ins.some(t=>t.witness.length!==0)}stripWitnesses(){this.ins.forEach(t=>{t.witness=aa})}weight(){const t=this.byteLength(!1),r=this.byteLength(!0);return t*3+r}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(t=!0){const r=t&&this.hasWitnesses();return(r?10:8)+Be.varuint.encodingLength(this.ins.length)+Be.varuint.encodingLength(this.outs.length)+this.ins.reduce((n,i)=>n+40+Dt(i.script),0)+this.outs.reduce((n,i)=>n+8+Dt(i.script),0)+(r?this.ins.reduce((n,i)=>n+KE(i.witness),0):0)}clone(){const t=new ae;return t.version=this.version,t.locktime=this.locktime,t.ins=this.ins.map(r=>({hash:r.hash,index:r.index,script:r.script,sequence:r.sequence,witness:r.witness})),t.outs=this.outs.map(r=>({script:r.script,value:r.value})),t}hashForSignature(t,r,n){if(Ht(ue.tuple(ue.UInt32,ue.Buffer,ue.Number),arguments),t>=this.ins.length)return Td;const i=Pd.compile(Pd.decompile(r).filter(a=>a!==WE.OPS.OP_CODESEPARATOR)),s=this.clone();if((n&31)===ae.SIGHASH_NONE)s.outs=[],s.ins.forEach((a,c)=>{c!==t&&(a.sequence=0)});else if((n&31)===ae.SIGHASH_SINGLE){if(t>=this.outs.length)return Td;s.outs.length=t+1;for(let a=0;a<t;a++)s.outs[a]=ZE;s.ins.forEach((a,c)=>{c!==t&&(a.sequence=0)})}n&ae.SIGHASH_ANYONECANPAY?(s.ins=[s.ins[t]],s.ins[0].script=i):(s.ins.forEach(a=>{a.script=_r}),s.ins[t].script=i);const o=Buffer.allocUnsafe(s.byteLength(!1)+4);return o.writeInt32LE(n,o.length-4),s.__toBuffer(o,0,!1),We.hash256(o)}hashForWitnessV1(t,r,n,i,s,o){if(Ht(ue.tuple(ue.UInt32,Ht.arrayOf(ue.Buffer),Ht.arrayOf(ue.Satoshi),ue.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=i===ae.SIGHASH_DEFAULT?ae.SIGHASH_ALL:i&ae.SIGHASH_OUTPUT_MASK,f=(i&ae.SIGHASH_INPUT_MASK)===ae.SIGHASH_ANYONECANPAY,u=a===ae.SIGHASH_NONE,d=a===ae.SIGHASH_SINGLE;let y=_r,p=_r,g=_r,b=_r,E=_r;if(!f){let _=Be.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(T=>{_.writeSlice(T.hash),_.writeUInt32(T.index)}),y=We.sha256(_.end()),_=Be.BufferWriter.withCapacity(8*this.ins.length),n.forEach(T=>_.writeUInt64(T)),p=We.sha256(_.end()),_=Be.BufferWriter.withCapacity(r.map(Dt).reduce((T,I)=>T+I)),r.forEach(T=>_.writeVarSlice(T)),g=We.sha256(_.end()),_=Be.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(T=>_.writeUInt32(T.sequence)),b=We.sha256(_.end())}if(u||d){if(d&&t<this.outs.length){const _=this.outs[t],T=Be.BufferWriter.withCapacity(8+Dt(_.script));T.writeUInt64(_.value),T.writeVarSlice(_.script),E=We.sha256(T.end())}}else{const _=this.outs.map(I=>8+Dt(I.script)).reduce((I,R)=>I+R),T=Be.BufferWriter.withCapacity(_);this.outs.forEach(I=>{T.writeUInt64(I.value),T.writeVarSlice(I.script)}),E=We.sha256(T.end())}const A=(s?2:0)+(o?1:0),P=174-(f?49:0)-(u?32:0)+(o?32:0)+(s?37:0),w=Be.BufferWriter.withCapacity(P);if(w.writeUInt8(i),w.writeInt32(this.version),w.writeUInt32(this.locktime),w.writeSlice(y),w.writeSlice(p),w.writeSlice(g),w.writeSlice(b),u||d||w.writeSlice(E),w.writeUInt8(A),f){const _=this.ins[t];w.writeSlice(_.hash),w.writeUInt32(_.index),w.writeUInt64(n[t]),w.writeVarSlice(r[t]),w.writeUInt32(_.sequence)}else w.writeUInt32(t);if(o){const _=Be.BufferWriter.withCapacity(Dt(o));_.writeVarSlice(o),w.writeSlice(We.sha256(_.end()))}return d&&w.writeSlice(E),s&&(w.writeSlice(s),w.writeUInt8(0),w.writeUInt32(4294967295)),We.taggedHash("TapSighash",Buffer.concat([Buffer.from([0]),w.end()]))}hashForWitnessV0(t,r,n,i){Ht(ue.tuple(ue.UInt32,ue.Buffer,ue.Satoshi,ue.UInt32),arguments);let s=Buffer.from([]),o,a=ca,c=ca,f=ca;if(i&ae.SIGHASH_ANYONECANPAY||(s=Buffer.allocUnsafe(36*this.ins.length),o=new Be.BufferWriter(s,0),this.ins.forEach(d=>{o.writeSlice(d.hash),o.writeUInt32(d.index)}),c=We.hash256(s)),!(i&ae.SIGHASH_ANYONECANPAY)&&(i&31)!==ae.SIGHASH_SINGLE&&(i&31)!==ae.SIGHASH_NONE&&(s=Buffer.allocUnsafe(4*this.ins.length),o=new Be.BufferWriter(s,0),this.ins.forEach(d=>{o.writeUInt32(d.sequence)}),f=We.hash256(s)),(i&31)!==ae.SIGHASH_SINGLE&&(i&31)!==ae.SIGHASH_NONE){const d=this.outs.reduce((y,p)=>y+8+Dt(p.script),0);s=Buffer.allocUnsafe(d),o=new Be.BufferWriter(s,0),this.outs.forEach(y=>{o.writeUInt64(y.value),o.writeVarSlice(y.script)}),a=We.hash256(s)}else if((i&31)===ae.SIGHASH_SINGLE&&t<this.outs.length){const d=this.outs[t];s=Buffer.allocUnsafe(8+Dt(d.script)),o=new Be.BufferWriter(s,0),o.writeUInt64(d.value),o.writeVarSlice(d.script),a=We.hash256(s)}s=Buffer.allocUnsafe(156+Dt(r)),o=new Be.BufferWriter(s,0);const u=this.ins[t];return o.writeInt32(this.version),o.writeSlice(c),o.writeSlice(f),o.writeSlice(u.hash),o.writeUInt32(u.index),o.writeVarSlice(r),o.writeUInt64(n),o.writeUInt32(u.sequence),o.writeSlice(a),o.writeUInt32(this.locktime),o.writeUInt32(i),We.hash256(s)}getHash(t){return t&&this.isCoinbase()?Buffer.alloc(32,0):We.hash256(this.__toBuffer(void 0,void 0,t))}getId(){return(0,Be.reverseBuffer)(this.getHash(!1)).toString("hex")}toBuffer(t,r){return this.__toBuffer(t,r,!0)}toHex(){return this.toBuffer(void 0,void 0).toString("hex")}setInputScript(t,r){Ht(ue.tuple(ue.Number,ue.Buffer),arguments),this.ins[t].script=r}setWitness(t,r){Ht(ue.tuple(ue.Number,[ue.Buffer]),arguments),this.ins[t].witness=r}__toBuffer(t,r,n=!1){t||(t=Buffer.allocUnsafe(this.byteLength(n)));const i=new Be.BufferWriter(t,r||0);i.writeInt32(this.version);const s=n&&this.hasWitnesses();return s&&(i.writeUInt8(ae.ADVANCED_TRANSACTION_MARKER),i.writeUInt8(ae.ADVANCED_TRANSACTION_FLAG)),i.writeVarInt(this.ins.length),this.ins.forEach(o=>{i.writeSlice(o.hash),i.writeUInt32(o.index),i.writeVarSlice(o.script),i.writeUInt32(o.sequence)}),i.writeVarInt(this.outs.length),this.outs.forEach(o=>{XE(o)?i.writeUInt64(o.value):i.writeSlice(o.valueBuffer),i.writeVarSlice(o.script)}),s&&this.ins.forEach(o=>{i.writeVector(o.witness)}),i.writeUInt32(this.locktime),r!==void 0?t.slice(r,i.offset):t}}fs.Transaction=ae;ae.DEFAULT_SEQUENCE=4294967295;ae.SIGHASH_DEFAULT=0;ae.SIGHASH_ALL=1;ae.SIGHASH_NONE=2;ae.SIGHASH_SINGLE=3;ae.SIGHASH_ANYONECANPAY=128;ae.SIGHASH_OUTPUT_MASK=3;ae.SIGHASH_INPUT_MASK=128;ae.ADVANCED_TRANSACTION_MARKER=0;ae.ADVANCED_TRANSACTION_FLAG=1;var me={},ds={};Object.defineProperty(ds,"__esModule",{value:!0});const JE=9007199254740991;function cf(e){if(e<0||e>JE||e%1!==0)throw new RangeError("value out of range")}function li(e,t,r){if(cf(e),t||(t=Buffer.allocUnsafe(iy(e))),!Buffer.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");return r||(r=0),e<253?(t.writeUInt8(e,r),Object.assign(li,{bytes:1})):e<=65535?(t.writeUInt8(253,r),t.writeUInt16LE(e,r+1),Object.assign(li,{bytes:3})):e<=4294967295?(t.writeUInt8(254,r),t.writeUInt32LE(e,r+1),Object.assign(li,{bytes:5})):(t.writeUInt8(255,r),t.writeUInt32LE(e>>>0,r+1),t.writeUInt32LE(e/4294967296|0,r+5),Object.assign(li,{bytes:9})),t}ds.encode=li;function pi(e,t){if(!Buffer.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");t||(t=0);const r=e.readUInt8(t);if(r<253)return Object.assign(pi,{bytes:1}),r;if(r===253)return Object.assign(pi,{bytes:3}),e.readUInt16LE(t+1);if(r===254)return Object.assign(pi,{bytes:5}),e.readUInt32LE(t+1);{Object.assign(pi,{bytes:9});const n=e.readUInt32LE(t+1),s=e.readUInt32LE(t+5)*4294967296+n;return cf(s),s}}ds.decode=pi;function iy(e){return cf(e),e<253?1:e<=65535?3:e<=4294967295?5:9}ds.encodingLength=iy;var ua={},To={},ze={};Object.defineProperty(ze,"__esModule",{value:!0});ze.testnet=ze.regtest=ze.bitcoin=void 0;ze.bitcoin={messagePrefix:`Bitcoin Signed Message:
50
+ */(function(e){const t=So,r=tf,n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=a,e.SlowBuffer=P,e.INSPECT_MAX_BYTES=50;const i=2147483647;e.kMaxLength=i,a.TYPED_ARRAY_SUPPORT=s(),!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 s(){try{const m=new Uint8Array(1),l={foo:function(){return 42}};return Object.setPrototypeOf(l,Uint8Array.prototype),Object.setPrototypeOf(m,l),m.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(m){if(m>i)throw new RangeError('The value "'+m+'" is invalid for option "size"');const l=new Uint8Array(m);return Object.setPrototypeOf(l,a.prototype),l}function a(m,l,h){if(typeof m=="number"){if(typeof l=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return d(m)}return c(m,l,h)}a.poolSize=8192;function c(m,l,h){if(typeof m=="string")return y(m,l);if(ArrayBuffer.isView(m))return g(m);if(m==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof m);if(Ve(m,ArrayBuffer)||m&&Ve(m.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Ve(m,SharedArrayBuffer)||m&&Ve(m.buffer,SharedArrayBuffer)))return b(m,l,h);if(typeof m=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const v=m.valueOf&&m.valueOf();if(v!=null&&v!==m)return a.from(v,l,h);const O=E(m);if(O)return O;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof m[Symbol.toPrimitive]=="function")return a.from(m[Symbol.toPrimitive]("string"),l,h);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof m)}a.from=function(m,l,h){return c(m,l,h)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function f(m){if(typeof m!="number")throw new TypeError('"size" argument must be of type number');if(m<0)throw new RangeError('The value "'+m+'" is invalid for option "size"')}function u(m,l,h){return f(m),m<=0?o(m):l!==void 0?typeof h=="string"?o(m).fill(l,h):o(m).fill(l):o(m)}a.alloc=function(m,l,h){return u(m,l,h)};function d(m){return f(m),o(m<0?0:A(m)|0)}a.allocUnsafe=function(m){return d(m)},a.allocUnsafeSlow=function(m){return d(m)};function y(m,l){if((typeof l!="string"||l==="")&&(l="utf8"),!a.isEncoding(l))throw new TypeError("Unknown encoding: "+l);const h=w(m,l)|0;let v=o(h);const O=v.write(m,l);return O!==h&&(v=v.slice(0,O)),v}function p(m){const l=m.length<0?0:A(m.length)|0,h=o(l);for(let v=0;v<l;v+=1)h[v]=m[v]&255;return h}function g(m){if(Ve(m,Uint8Array)){const l=new Uint8Array(m);return b(l.buffer,l.byteOffset,l.byteLength)}return p(m)}function b(m,l,h){if(l<0||m.byteLength<l)throw new RangeError('"offset" is outside of buffer bounds');if(m.byteLength<l+(h||0))throw new RangeError('"length" is outside of buffer bounds');let v;return l===void 0&&h===void 0?v=new Uint8Array(m):h===void 0?v=new Uint8Array(m,l):v=new Uint8Array(m,l,h),Object.setPrototypeOf(v,a.prototype),v}function E(m){if(a.isBuffer(m)){const l=A(m.length)|0,h=o(l);return h.length===0||m.copy(h,0,0,l),h}if(m.length!==void 0)return typeof m.length!="number"||hr(m.length)?o(0):p(m);if(m.type==="Buffer"&&Array.isArray(m.data))return p(m.data)}function A(m){if(m>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return m|0}function P(m){return+m!=m&&(m=0),a.alloc(+m)}a.isBuffer=function(l){return l!=null&&l._isBuffer===!0&&l!==a.prototype},a.compare=function(l,h){if(Ve(l,Uint8Array)&&(l=a.from(l,l.offset,l.byteLength)),Ve(h,Uint8Array)&&(h=a.from(h,h.offset,h.byteLength)),!a.isBuffer(l)||!a.isBuffer(h))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(l===h)return 0;let v=l.length,O=h.length;for(let F=0,z=Math.min(v,O);F<z;++F)if(l[F]!==h[F]){v=l[F],O=h[F];break}return v<O?-1:O<v?1:0},a.isEncoding=function(l){switch(String(l).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(l,h){if(!Array.isArray(l))throw new TypeError('"list" argument must be an Array of Buffers');if(l.length===0)return a.alloc(0);let v;if(h===void 0)for(h=0,v=0;v<l.length;++v)h+=l[v].length;const O=a.allocUnsafe(h);let F=0;for(v=0;v<l.length;++v){let z=l[v];if(Ve(z,Uint8Array))F+z.length>O.length?(a.isBuffer(z)||(z=a.from(z)),z.copy(O,F)):Uint8Array.prototype.set.call(O,z,F);else if(a.isBuffer(z))z.copy(O,F);else throw new TypeError('"list" argument must be an Array of Buffers');F+=z.length}return O};function w(m,l){if(a.isBuffer(m))return m.length;if(ArrayBuffer.isView(m)||Ve(m,ArrayBuffer))return m.byteLength;if(typeof m!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof m);const h=m.length,v=arguments.length>2&&arguments[2]===!0;if(!v&&h===0)return 0;let O=!1;for(;;)switch(l){case"ascii":case"latin1":case"binary":return h;case"utf8":case"utf-8":return Rt(m).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return h*2;case"hex":return h>>>1;case"base64":return Nt(m).length;default:if(O)return v?-1:Rt(m).length;l=(""+l).toLowerCase(),O=!0}}a.byteLength=w;function _(m,l,h){let v=!1;if((l===void 0||l<0)&&(l=0),l>this.length||((h===void 0||h>this.length)&&(h=this.length),h<=0)||(h>>>=0,l>>>=0,h<=l))return"";for(m||(m="utf8");;)switch(m){case"hex":return B(this,l,h);case"utf8":case"utf-8":return V(this,l,h);case"ascii":return J(this,l,h);case"latin1":case"binary":return M(this,l,h);case"base64":return j(this,l,h);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return q(this,l,h);default:if(v)throw new TypeError("Unknown encoding: "+m);m=(m+"").toLowerCase(),v=!0}}a.prototype._isBuffer=!0;function T(m,l,h){const v=m[l];m[l]=m[h],m[h]=v}a.prototype.swap16=function(){const l=this.length;if(l%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let h=0;h<l;h+=2)T(this,h,h+1);return this},a.prototype.swap32=function(){const l=this.length;if(l%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let h=0;h<l;h+=4)T(this,h,h+3),T(this,h+1,h+2);return this},a.prototype.swap64=function(){const l=this.length;if(l%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let h=0;h<l;h+=8)T(this,h,h+7),T(this,h+1,h+6),T(this,h+2,h+5),T(this,h+3,h+4);return this},a.prototype.toString=function(){const l=this.length;return l===0?"":arguments.length===0?V(this,0,l):_.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(l){if(!a.isBuffer(l))throw new TypeError("Argument must be a Buffer");return this===l?!0:a.compare(this,l)===0},a.prototype.inspect=function(){let l="";const h=e.INSPECT_MAX_BYTES;return l=this.toString("hex",0,h).replace(/(.{2})/g,"$1 ").trim(),this.length>h&&(l+=" ... "),"<Buffer "+l+">"},n&&(a.prototype[n]=a.prototype.inspect),a.prototype.compare=function(l,h,v,O,F){if(Ve(l,Uint8Array)&&(l=a.from(l,l.offset,l.byteLength)),!a.isBuffer(l))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof l);if(h===void 0&&(h=0),v===void 0&&(v=l?l.length:0),O===void 0&&(O=0),F===void 0&&(F=this.length),h<0||v>l.length||O<0||F>this.length)throw new RangeError("out of range index");if(O>=F&&h>=v)return 0;if(O>=F)return-1;if(h>=v)return 1;if(h>>>=0,v>>>=0,O>>>=0,F>>>=0,this===l)return 0;let z=F-O,ce=v-h;const Pe=Math.min(z,ce),we=this.slice(O,F),Te=l.slice(h,v);for(let ye=0;ye<Pe;++ye)if(we[ye]!==Te[ye]){z=we[ye],ce=Te[ye];break}return z<ce?-1:ce<z?1:0};function I(m,l,h,v,O){if(m.length===0)return-1;if(typeof h=="string"?(v=h,h=0):h>2147483647?h=2147483647:h<-2147483648&&(h=-2147483648),h=+h,hr(h)&&(h=O?0:m.length-1),h<0&&(h=m.length+h),h>=m.length){if(O)return-1;h=m.length-1}else if(h<0)if(O)h=0;else return-1;if(typeof l=="string"&&(l=a.from(l,v)),a.isBuffer(l))return l.length===0?-1:R(m,l,h,v,O);if(typeof l=="number")return l=l&255,typeof Uint8Array.prototype.indexOf=="function"?O?Uint8Array.prototype.indexOf.call(m,l,h):Uint8Array.prototype.lastIndexOf.call(m,l,h):R(m,[l],h,v,O);throw new TypeError("val must be string, number or Buffer")}function R(m,l,h,v,O){let F=1,z=m.length,ce=l.length;if(v!==void 0&&(v=String(v).toLowerCase(),v==="ucs2"||v==="ucs-2"||v==="utf16le"||v==="utf-16le")){if(m.length<2||l.length<2)return-1;F=2,z/=2,ce/=2,h/=2}function Pe(Te,ye){return F===1?Te[ye]:Te.readUInt16BE(ye*F)}let we;if(O){let Te=-1;for(we=h;we<z;we++)if(Pe(m,we)===Pe(l,Te===-1?0:we-Te)){if(Te===-1&&(Te=we),we-Te+1===ce)return Te*F}else Te!==-1&&(we-=we-Te),Te=-1}else for(h+ce>z&&(h=z-ce),we=h;we>=0;we--){let Te=!0;for(let ye=0;ye<ce;ye++)if(Pe(m,we+ye)!==Pe(l,ye)){Te=!1;break}if(Te)return we}return-1}a.prototype.includes=function(l,h,v){return this.indexOf(l,h,v)!==-1},a.prototype.indexOf=function(l,h,v){return I(this,l,h,v,!0)},a.prototype.lastIndexOf=function(l,h,v){return I(this,l,h,v,!1)};function L(m,l,h,v){h=Number(h)||0;const O=m.length-h;v?(v=Number(v),v>O&&(v=O)):v=O;const F=l.length;v>F/2&&(v=F/2);let z;for(z=0;z<v;++z){const ce=parseInt(l.substr(z*2,2),16);if(hr(ce))return z;m[h+z]=ce}return z}function S(m,l,h,v){return Ge(Rt(l,m.length-h),m,h,v)}function $(m,l,h,v){return Ge(Fr(l),m,h,v)}function C(m,l,h,v){return Ge(Nt(l),m,h,v)}function U(m,l,h,v){return Ge(G(l,m.length-h),m,h,v)}a.prototype.write=function(l,h,v,O){if(h===void 0)O="utf8",v=this.length,h=0;else if(v===void 0&&typeof h=="string")O=h,v=this.length,h=0;else if(isFinite(h))h=h>>>0,isFinite(v)?(v=v>>>0,O===void 0&&(O="utf8")):(O=v,v=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const F=this.length-h;if((v===void 0||v>F)&&(v=F),l.length>0&&(v<0||h<0)||h>this.length)throw new RangeError("Attempt to write outside buffer bounds");O||(O="utf8");let z=!1;for(;;)switch(O){case"hex":return L(this,l,h,v);case"utf8":case"utf-8":return S(this,l,h,v);case"ascii":case"latin1":case"binary":return $(this,l,h,v);case"base64":return C(this,l,h,v);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return U(this,l,h,v);default:if(z)throw new TypeError("Unknown encoding: "+O);O=(""+O).toLowerCase(),z=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function j(m,l,h){return l===0&&h===m.length?t.fromByteArray(m):t.fromByteArray(m.slice(l,h))}function V(m,l,h){h=Math.min(m.length,h);const v=[];let O=l;for(;O<h;){const F=m[O];let z=null,ce=F>239?4:F>223?3:F>191?2:1;if(O+ce<=h){let Pe,we,Te,ye;switch(ce){case 1:F<128&&(z=F);break;case 2:Pe=m[O+1],(Pe&192)===128&&(ye=(F&31)<<6|Pe&63,ye>127&&(z=ye));break;case 3:Pe=m[O+1],we=m[O+2],(Pe&192)===128&&(we&192)===128&&(ye=(F&15)<<12|(Pe&63)<<6|we&63,ye>2047&&(ye<55296||ye>57343)&&(z=ye));break;case 4:Pe=m[O+1],we=m[O+2],Te=m[O+3],(Pe&192)===128&&(we&192)===128&&(Te&192)===128&&(ye=(F&15)<<18|(Pe&63)<<12|(we&63)<<6|Te&63,ye>65535&&ye<1114112&&(z=ye))}}z===null?(z=65533,ce=1):z>65535&&(z-=65536,v.push(z>>>10&1023|55296),z=56320|z&1023),v.push(z),O+=ce}return X(v)}const Y=4096;function X(m){const l=m.length;if(l<=Y)return String.fromCharCode.apply(String,m);let h="",v=0;for(;v<l;)h+=String.fromCharCode.apply(String,m.slice(v,v+=Y));return h}function J(m,l,h){let v="";h=Math.min(m.length,h);for(let O=l;O<h;++O)v+=String.fromCharCode(m[O]&127);return v}function M(m,l,h){let v="";h=Math.min(m.length,h);for(let O=l;O<h;++O)v+=String.fromCharCode(m[O]);return v}function B(m,l,h){const v=m.length;(!l||l<0)&&(l=0),(!h||h<0||h>v)&&(h=v);let O="";for(let F=l;F<h;++F)O+=ln[m[F]];return O}function q(m,l,h){const v=m.slice(l,h);let O="";for(let F=0;F<v.length-1;F+=2)O+=String.fromCharCode(v[F]+v[F+1]*256);return O}a.prototype.slice=function(l,h){const v=this.length;l=~~l,h=h===void 0?v:~~h,l<0?(l+=v,l<0&&(l=0)):l>v&&(l=v),h<0?(h+=v,h<0&&(h=0)):h>v&&(h=v),h<l&&(h=l);const O=this.subarray(l,h);return Object.setPrototypeOf(O,a.prototype),O};function W(m,l,h){if(m%1!==0||m<0)throw new RangeError("offset is not uint");if(m+l>h)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(l,h,v){l=l>>>0,h=h>>>0,v||W(l,h,this.length);let O=this[l],F=1,z=0;for(;++z<h&&(F*=256);)O+=this[l+z]*F;return O},a.prototype.readUintBE=a.prototype.readUIntBE=function(l,h,v){l=l>>>0,h=h>>>0,v||W(l,h,this.length);let O=this[l+--h],F=1;for(;h>0&&(F*=256);)O+=this[l+--h]*F;return O},a.prototype.readUint8=a.prototype.readUInt8=function(l,h){return l=l>>>0,h||W(l,1,this.length),this[l]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(l,h){return l=l>>>0,h||W(l,2,this.length),this[l]|this[l+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(l,h){return l=l>>>0,h||W(l,2,this.length),this[l]<<8|this[l+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(l,h){return l=l>>>0,h||W(l,4,this.length),(this[l]|this[l+1]<<8|this[l+2]<<16)+this[l+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(l,h){return l=l>>>0,h||W(l,4,this.length),this[l]*16777216+(this[l+1]<<16|this[l+2]<<8|this[l+3])},a.prototype.readBigUInt64LE=yr(function(l){l=l>>>0,he(l,"offset");const h=this[l],v=this[l+7];(h===void 0||v===void 0)&&Ae(l,this.length-8);const O=h+this[++l]*2**8+this[++l]*2**16+this[++l]*2**24,F=this[++l]+this[++l]*2**8+this[++l]*2**16+v*2**24;return BigInt(O)+(BigInt(F)<<BigInt(32))}),a.prototype.readBigUInt64BE=yr(function(l){l=l>>>0,he(l,"offset");const h=this[l],v=this[l+7];(h===void 0||v===void 0)&&Ae(l,this.length-8);const O=h*2**24+this[++l]*2**16+this[++l]*2**8+this[++l],F=this[++l]*2**24+this[++l]*2**16+this[++l]*2**8+v;return(BigInt(O)<<BigInt(32))+BigInt(F)}),a.prototype.readIntLE=function(l,h,v){l=l>>>0,h=h>>>0,v||W(l,h,this.length);let O=this[l],F=1,z=0;for(;++z<h&&(F*=256);)O+=this[l+z]*F;return F*=128,O>=F&&(O-=Math.pow(2,8*h)),O},a.prototype.readIntBE=function(l,h,v){l=l>>>0,h=h>>>0,v||W(l,h,this.length);let O=h,F=1,z=this[l+--O];for(;O>0&&(F*=256);)z+=this[l+--O]*F;return F*=128,z>=F&&(z-=Math.pow(2,8*h)),z},a.prototype.readInt8=function(l,h){return l=l>>>0,h||W(l,1,this.length),this[l]&128?(255-this[l]+1)*-1:this[l]},a.prototype.readInt16LE=function(l,h){l=l>>>0,h||W(l,2,this.length);const v=this[l]|this[l+1]<<8;return v&32768?v|4294901760:v},a.prototype.readInt16BE=function(l,h){l=l>>>0,h||W(l,2,this.length);const v=this[l+1]|this[l]<<8;return v&32768?v|4294901760:v},a.prototype.readInt32LE=function(l,h){return l=l>>>0,h||W(l,4,this.length),this[l]|this[l+1]<<8|this[l+2]<<16|this[l+3]<<24},a.prototype.readInt32BE=function(l,h){return l=l>>>0,h||W(l,4,this.length),this[l]<<24|this[l+1]<<16|this[l+2]<<8|this[l+3]},a.prototype.readBigInt64LE=yr(function(l){l=l>>>0,he(l,"offset");const h=this[l],v=this[l+7];(h===void 0||v===void 0)&&Ae(l,this.length-8);const O=this[l+4]+this[l+5]*2**8+this[l+6]*2**16+(v<<24);return(BigInt(O)<<BigInt(32))+BigInt(h+this[++l]*2**8+this[++l]*2**16+this[++l]*2**24)}),a.prototype.readBigInt64BE=yr(function(l){l=l>>>0,he(l,"offset");const h=this[l],v=this[l+7];(h===void 0||v===void 0)&&Ae(l,this.length-8);const O=(h<<24)+this[++l]*2**16+this[++l]*2**8+this[++l];return(BigInt(O)<<BigInt(32))+BigInt(this[++l]*2**24+this[++l]*2**16+this[++l]*2**8+v)}),a.prototype.readFloatLE=function(l,h){return l=l>>>0,h||W(l,4,this.length),r.read(this,l,!0,23,4)},a.prototype.readFloatBE=function(l,h){return l=l>>>0,h||W(l,4,this.length),r.read(this,l,!1,23,4)},a.prototype.readDoubleLE=function(l,h){return l=l>>>0,h||W(l,8,this.length),r.read(this,l,!0,52,8)},a.prototype.readDoubleBE=function(l,h){return l=l>>>0,h||W(l,8,this.length),r.read(this,l,!1,52,8)};function k(m,l,h,v,O,F){if(!a.isBuffer(m))throw new TypeError('"buffer" argument must be a Buffer instance');if(l>O||l<F)throw new RangeError('"value" argument is out of bounds');if(h+v>m.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(l,h,v,O){if(l=+l,h=h>>>0,v=v>>>0,!O){const ce=Math.pow(2,8*v)-1;k(this,l,h,v,ce,0)}let F=1,z=0;for(this[h]=l&255;++z<v&&(F*=256);)this[h+z]=l/F&255;return h+v},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(l,h,v,O){if(l=+l,h=h>>>0,v=v>>>0,!O){const ce=Math.pow(2,8*v)-1;k(this,l,h,v,ce,0)}let F=v-1,z=1;for(this[h+F]=l&255;--F>=0&&(z*=256);)this[h+F]=l/z&255;return h+v},a.prototype.writeUint8=a.prototype.writeUInt8=function(l,h,v){return l=+l,h=h>>>0,v||k(this,l,h,1,255,0),this[h]=l&255,h+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(l,h,v){return l=+l,h=h>>>0,v||k(this,l,h,2,65535,0),this[h]=l&255,this[h+1]=l>>>8,h+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(l,h,v){return l=+l,h=h>>>0,v||k(this,l,h,2,65535,0),this[h]=l>>>8,this[h+1]=l&255,h+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(l,h,v){return l=+l,h=h>>>0,v||k(this,l,h,4,4294967295,0),this[h+3]=l>>>24,this[h+2]=l>>>16,this[h+1]=l>>>8,this[h]=l&255,h+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(l,h,v){return l=+l,h=h>>>0,v||k(this,l,h,4,4294967295,0),this[h]=l>>>24,this[h+1]=l>>>16,this[h+2]=l>>>8,this[h+3]=l&255,h+4};function N(m,l,h,v,O){de(l,v,O,m,h,7);let F=Number(l&BigInt(4294967295));m[h++]=F,F=F>>8,m[h++]=F,F=F>>8,m[h++]=F,F=F>>8,m[h++]=F;let z=Number(l>>BigInt(32)&BigInt(4294967295));return m[h++]=z,z=z>>8,m[h++]=z,z=z>>8,m[h++]=z,z=z>>8,m[h++]=z,h}function H(m,l,h,v,O){de(l,v,O,m,h,7);let F=Number(l&BigInt(4294967295));m[h+7]=F,F=F>>8,m[h+6]=F,F=F>>8,m[h+5]=F,F=F>>8,m[h+4]=F;let z=Number(l>>BigInt(32)&BigInt(4294967295));return m[h+3]=z,z=z>>8,m[h+2]=z,z=z>>8,m[h+1]=z,z=z>>8,m[h]=z,h+8}a.prototype.writeBigUInt64LE=yr(function(l,h=0){return N(this,l,h,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=yr(function(l,h=0){return H(this,l,h,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(l,h,v,O){if(l=+l,h=h>>>0,!O){const Pe=Math.pow(2,8*v-1);k(this,l,h,v,Pe-1,-Pe)}let F=0,z=1,ce=0;for(this[h]=l&255;++F<v&&(z*=256);)l<0&&ce===0&&this[h+F-1]!==0&&(ce=1),this[h+F]=(l/z>>0)-ce&255;return h+v},a.prototype.writeIntBE=function(l,h,v,O){if(l=+l,h=h>>>0,!O){const Pe=Math.pow(2,8*v-1);k(this,l,h,v,Pe-1,-Pe)}let F=v-1,z=1,ce=0;for(this[h+F]=l&255;--F>=0&&(z*=256);)l<0&&ce===0&&this[h+F+1]!==0&&(ce=1),this[h+F]=(l/z>>0)-ce&255;return h+v},a.prototype.writeInt8=function(l,h,v){return l=+l,h=h>>>0,v||k(this,l,h,1,127,-128),l<0&&(l=255+l+1),this[h]=l&255,h+1},a.prototype.writeInt16LE=function(l,h,v){return l=+l,h=h>>>0,v||k(this,l,h,2,32767,-32768),this[h]=l&255,this[h+1]=l>>>8,h+2},a.prototype.writeInt16BE=function(l,h,v){return l=+l,h=h>>>0,v||k(this,l,h,2,32767,-32768),this[h]=l>>>8,this[h+1]=l&255,h+2},a.prototype.writeInt32LE=function(l,h,v){return l=+l,h=h>>>0,v||k(this,l,h,4,2147483647,-2147483648),this[h]=l&255,this[h+1]=l>>>8,this[h+2]=l>>>16,this[h+3]=l>>>24,h+4},a.prototype.writeInt32BE=function(l,h,v){return l=+l,h=h>>>0,v||k(this,l,h,4,2147483647,-2147483648),l<0&&(l=4294967295+l+1),this[h]=l>>>24,this[h+1]=l>>>16,this[h+2]=l>>>8,this[h+3]=l&255,h+4},a.prototype.writeBigInt64LE=yr(function(l,h=0){return N(this,l,h,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=yr(function(l,h=0){return H(this,l,h,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Z(m,l,h,v,O,F){if(h+v>m.length)throw new RangeError("Index out of range");if(h<0)throw new RangeError("Index out of range")}function Q(m,l,h,v,O){return l=+l,h=h>>>0,O||Z(m,l,h,4),r.write(m,l,h,v,23,4),h+4}a.prototype.writeFloatLE=function(l,h,v){return Q(this,l,h,!0,v)},a.prototype.writeFloatBE=function(l,h,v){return Q(this,l,h,!1,v)};function ie(m,l,h,v,O){return l=+l,h=h>>>0,O||Z(m,l,h,8),r.write(m,l,h,v,52,8),h+8}a.prototype.writeDoubleLE=function(l,h,v){return ie(this,l,h,!0,v)},a.prototype.writeDoubleBE=function(l,h,v){return ie(this,l,h,!1,v)},a.prototype.copy=function(l,h,v,O){if(!a.isBuffer(l))throw new TypeError("argument should be a Buffer");if(v||(v=0),!O&&O!==0&&(O=this.length),h>=l.length&&(h=l.length),h||(h=0),O>0&&O<v&&(O=v),O===v||l.length===0||this.length===0)return 0;if(h<0)throw new RangeError("targetStart out of bounds");if(v<0||v>=this.length)throw new RangeError("Index out of range");if(O<0)throw new RangeError("sourceEnd out of bounds");O>this.length&&(O=this.length),l.length-h<O-v&&(O=l.length-h+v);const F=O-v;return this===l&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(h,v,O):Uint8Array.prototype.set.call(l,this.subarray(v,O),h),F},a.prototype.fill=function(l,h,v,O){if(typeof l=="string"){if(typeof h=="string"?(O=h,h=0,v=this.length):typeof v=="string"&&(O=v,v=this.length),O!==void 0&&typeof O!="string")throw new TypeError("encoding must be a string");if(typeof O=="string"&&!a.isEncoding(O))throw new TypeError("Unknown encoding: "+O);if(l.length===1){const z=l.charCodeAt(0);(O==="utf8"&&z<128||O==="latin1")&&(l=z)}}else typeof l=="number"?l=l&255:typeof l=="boolean"&&(l=Number(l));if(h<0||this.length<h||this.length<v)throw new RangeError("Out of range index");if(v<=h)return this;h=h>>>0,v=v===void 0?this.length:v>>>0,l||(l=0);let F;if(typeof l=="number")for(F=h;F<v;++F)this[F]=l;else{const z=a.isBuffer(l)?l:a.from(l,O),ce=z.length;if(ce===0)throw new TypeError('The value "'+l+'" is invalid for argument "value"');for(F=0;F<v-h;++F)this[F+h]=z[F%ce]}return this};const ne={};function re(m,l,h){ne[m]=class extends h{constructor(){super(),Object.defineProperty(this,"message",{value:l.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${m}]`,this.stack,delete this.name}get code(){return m}set code(O){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:O,writable:!0})}toString(){return`${this.name} [${m}]: ${this.message}`}}}re("ERR_BUFFER_OUT_OF_BOUNDS",function(m){return m?`${m} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),re("ERR_INVALID_ARG_TYPE",function(m,l){return`The "${m}" argument must be of type number. Received type ${typeof l}`},TypeError),re("ERR_OUT_OF_RANGE",function(m,l,h){let v=`The value of "${m}" is out of range.`,O=h;return Number.isInteger(h)&&Math.abs(h)>2**32?O=te(String(h)):typeof h=="bigint"&&(O=String(h),(h>BigInt(2)**BigInt(32)||h<-(BigInt(2)**BigInt(32)))&&(O=te(O)),O+="n"),v+=` It must be ${l}. Received ${O}`,v},RangeError);function te(m){let l="",h=m.length;const v=m[0]==="-"?1:0;for(;h>=v+4;h-=3)l=`_${m.slice(h-3,h)}${l}`;return`${m.slice(0,h)}${l}`}function se(m,l,h){he(l,"offset"),(m[l]===void 0||m[l+h]===void 0)&&Ae(l,m.length-(h+1))}function de(m,l,h,v,O,F){if(m>h||m<l){const z=typeof l=="bigint"?"n":"";let ce;throw l===0||l===BigInt(0)?ce=`>= 0${z} and < 2${z} ** ${(F+1)*8}${z}`:ce=`>= -(2${z} ** ${(F+1)*8-1}${z}) and < 2 ** ${(F+1)*8-1}${z}`,new ne.ERR_OUT_OF_RANGE("value",ce,m)}se(v,O,F)}function he(m,l){if(typeof m!="number")throw new ne.ERR_INVALID_ARG_TYPE(l,"number",m)}function Ae(m,l,h){throw Math.floor(m)!==m?(he(m,h),new ne.ERR_OUT_OF_RANGE("offset","an integer",m)):l<0?new ne.ERR_BUFFER_OUT_OF_BOUNDS:new ne.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${l}`,m)}const at=/[^+/0-9A-Za-z-_]/g;function Re(m){if(m=m.split("=")[0],m=m.trim().replace(at,""),m.length<2)return"";for(;m.length%4!==0;)m=m+"=";return m}function Rt(m,l){l=l||1/0;let h;const v=m.length;let O=null;const F=[];for(let z=0;z<v;++z){if(h=m.charCodeAt(z),h>55295&&h<57344){if(!O){if(h>56319){(l-=3)>-1&&F.push(239,191,189);continue}else if(z+1===v){(l-=3)>-1&&F.push(239,191,189);continue}O=h;continue}if(h<56320){(l-=3)>-1&&F.push(239,191,189),O=h;continue}h=(O-55296<<10|h-56320)+65536}else O&&(l-=3)>-1&&F.push(239,191,189);if(O=null,h<128){if((l-=1)<0)break;F.push(h)}else if(h<2048){if((l-=2)<0)break;F.push(h>>6|192,h&63|128)}else if(h<65536){if((l-=3)<0)break;F.push(h>>12|224,h>>6&63|128,h&63|128)}else if(h<1114112){if((l-=4)<0)break;F.push(h>>18|240,h>>12&63|128,h>>6&63|128,h&63|128)}else throw new Error("Invalid code point")}return F}function Fr(m){const l=[];for(let h=0;h<m.length;++h)l.push(m.charCodeAt(h)&255);return l}function G(m,l){let h,v,O;const F=[];for(let z=0;z<m.length&&!((l-=2)<0);++z)h=m.charCodeAt(z),v=h>>8,O=h%256,F.push(O),F.push(v);return F}function Nt(m){return t.toByteArray(Re(m))}function Ge(m,l,h,v){let O;for(O=0;O<v&&!(O+h>=l.length||O>=m.length);++O)l[O+h]=m[O];return O}function Ve(m,l){return m instanceof l||m!=null&&m.constructor!=null&&m.constructor.name!=null&&m.constructor.name===l.name}function hr(m){return m!==m}const ln=function(){const m="0123456789abcdef",l=new Array(256);for(let h=0;h<16;++h){const v=h*16;for(let O=0;O<16;++O)l[v+O]=m[h]+m[O]}return l}();function yr(m){return typeof BigInt>"u"?Ly:m}function Ly(){throw new Error("BigInt not supported")}})(un);var Yi={Array:function(e){return e!=null&&e.constructor===Array},Boolean:function(e){return typeof e=="boolean"},Function:function(e){return typeof e=="function"},Nil:function(e){return e==null},Number:function(e){return typeof e=="number"},Object:function(e){return typeof e=="object"},String:function(e){return typeof e=="string"},"":function(){return!0}};Yi.Null=Yi.Nil;for(var vd in Yi)Yi[vd].toJSON=(function(e){return e}).bind(null,vd);var rf=Yi,qr=rf;function $0(e){return e.name||e.toString().match(/function (.*?)\s*\(/)[1]}function nf(e){return qr.Nil(e)?"":$0(e.constructor)}function mE(e){return qr.Function(e)?"":qr.String(e)?JSON.stringify(e):e&&qr.Object(e)?"":e}function sf(e,t){Error.captureStackTrace&&Error.captureStackTrace(e,t)}function Ys(e){return qr.Function(e)?e.toJSON?e.toJSON():$0(e):qr.Array(e)?"Array":e&&qr.Object(e)?"Object":e!==void 0?e:""}function U0(e,t,r){var n=mE(t);return"Expected "+Ys(e)+", got"+(r!==""?" "+r:"")+(n!==""?" "+n:"")}function fr(e,t,r){r=r||nf(t),this.message=U0(e,t,r),sf(this,fr),this.__type=e,this.__value=t,this.__valueTypeName=r}fr.prototype=Object.create(Error.prototype);fr.prototype.constructor=fr;function gE(e,t,r,n,i){var s='" of type ';return t==="key"&&(s='" with key type '),U0('property "'+Ys(r)+s+Ys(e),n,i)}function kn(e,t,r,n,i){e?(i=i||nf(n),this.message=gE(e,r,t,n,i)):this.message='Unexpected property "'+t+'"',sf(this,fr),this.__label=r,this.__property=t,this.__type=e,this.__value=n,this.__valueTypeName=i}kn.prototype=Object.create(Error.prototype);kn.prototype.constructor=fr;function bE(e,t){return new fr(e,{},t)}function wE(e,t,r){return e instanceof kn?(t=t+"."+e.__property,e=new kn(e.__type,t,e.__label,e.__value,e.__valueTypeName)):e instanceof fr&&(e=new kn(e.__type,t,r,e.__value,e.__valueTypeName)),sf(e),e}var H0={TfTypeError:fr,TfPropertyTypeError:kn,tfCustomError:bE,tfSubError:wE,tfJSON:Ys,getValueTypeName:nf},ia,Ed;function vE(){if(Ed)return ia;Ed=1;var e=rf,t=H0;function r(I){return Buffer.isBuffer(I)}function n(I){return typeof I=="string"&&/^([0-9a-f]{2})+$/i.test(I)}function i(I,R){var L=I.toJSON();function S($){if(!I($))return!1;if($.length===R)return!0;throw t.tfCustomError(L+"(Length: "+R+")",L+"(Length: "+$.length+")")}return S.toJSON=function(){return L},S}var s=i.bind(null,e.Array),o=i.bind(null,r),a=i.bind(null,n),c=i.bind(null,e.String);function f(I,R,L){L=L||e.Number;function S($,C){return L($,C)&&$>I&&$<R}return S.toJSON=function(){return`${L.toJSON()} between [${I}, ${R}]`},S}var u=Math.pow(2,53)-1;function d(I){return typeof I=="number"&&isFinite(I)}function y(I){return I<<24>>24===I}function p(I){return I<<16>>16===I}function g(I){return(I|0)===I}function b(I){return typeof I=="number"&&I>=-u&&I<=u&&Math.floor(I)===I}function E(I){return(I&255)===I}function A(I){return(I&65535)===I}function P(I){return I>>>0===I}function w(I){return typeof I=="number"&&I>=0&&I<=u&&Math.floor(I)===I}var _={ArrayN:s,Buffer:r,BufferN:o,Finite:d,Hex:n,HexN:a,Int8:y,Int16:p,Int32:g,Int53:b,Range:f,StringN:c,UInt8:E,UInt16:A,UInt32:P,UInt53:w};for(var T in _)_[T].toJSON=(function(I){return I}).bind(null,T);return ia=_,ia}var us=H0,He=rf,Jt=us.tfJSON,L0=us.TfTypeError,M0=us.TfPropertyTypeError,ii=us.tfSubError,EE=us.getValueTypeName,ir={arrayOf:function(t,r){t=zt(t),r=r||{};function n(i,s){return!He.Array(i)||He.Nil(i)||r.minLength!==void 0&&i.length<r.minLength||r.maxLength!==void 0&&i.length>r.maxLength||r.length!==void 0&&i.length!==r.length?!1:i.every(function(o,a){try{return Xe(t,o,s)}catch(c){throw ii(c,a)}})}return n.toJSON=function(){var i="["+Jt(t)+"]";return r.length!==void 0?i+="{"+r.length+"}":(r.minLength!==void 0||r.maxLength!==void 0)&&(i+="{"+(r.minLength===void 0?0:r.minLength)+","+(r.maxLength===void 0?1/0:r.maxLength)+"}"),i},n},maybe:function e(t){t=zt(t);function r(n,i){return He.Nil(n)||t(n,i,e)}return r.toJSON=function(){return"?"+Jt(t)},r},map:function(t,r){t=zt(t),r&&(r=zt(r));function n(i,s){if(!He.Object(i)||He.Nil(i))return!1;for(var o in i){try{r&&Xe(r,o,s)}catch(c){throw ii(c,o,"key")}try{var a=i[o];Xe(t,a,s)}catch(c){throw ii(c,o)}}return!0}return r?n.toJSON=function(){return"{"+Jt(r)+": "+Jt(t)+"}"}:n.toJSON=function(){return"{"+Jt(t)+"}"},n},object:function(t){var r={};for(var n in t)r[n]=zt(t[n]);function i(s,o){if(!He.Object(s)||He.Nil(s))return!1;var a;try{for(a in r){var c=r[a],f=s[a];Xe(c,f,o)}}catch(u){throw ii(u,a)}if(o){for(a in s)if(!r[a])throw new M0(void 0,a)}return!0}return i.toJSON=function(){return Jt(r)},i},anyOf:function(){var t=[].slice.call(arguments).map(zt);function r(n,i){return t.some(function(s){try{return Xe(s,n,i)}catch{return!1}})}return r.toJSON=function(){return t.map(Jt).join("|")},r},allOf:function(){var t=[].slice.call(arguments).map(zt);function r(n,i){return t.every(function(s){try{return Xe(s,n,i)}catch{return!1}})}return r.toJSON=function(){return t.map(Jt).join(" & ")},r},quacksLike:function(t){function r(n){return t===EE(n)}return r.toJSON=function(){return t},r},tuple:function(){var t=[].slice.call(arguments).map(zt);function r(n,i){return He.Nil(n)||He.Nil(n.length)||i&&n.length!==t.length?!1:t.every(function(s,o){try{return Xe(s,n[o],i)}catch(a){throw ii(a,o)}})}return r.toJSON=function(){return"("+t.map(Jt).join(", ")+")"},r},value:function(t){function r(n){return n===t}return r.toJSON=function(){return t},r}};ir.oneOf=ir.anyOf;function zt(e){if(He.String(e))return e[0]==="?"?ir.maybe(e.slice(1)):He[e]||ir.quacksLike(e);if(e&&He.Object(e)){if(He.Array(e)){if(e.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return ir.arrayOf(e[0])}return ir.object(e)}else if(He.Function(e))return e;return ir.value(e)}function Xe(e,t,r,n){if(He.Function(e)){if(e(t,r))return!0;throw new L0(n||e,t)}return Xe(zt(e),t,r)}for(var Ir in He)Xe[Ir]=He[Ir];for(Ir in ir)Xe[Ir]=ir[Ir];var xd=vE();for(Ir in xd)Xe[Ir]=xd[Ir];Xe.compile=zt;Xe.TfTypeError=L0;Xe.TfPropertyTypeError=M0;var xE=Xe;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.oneOf=e.Null=e.BufferN=e.Function=e.UInt32=e.UInt8=e.tuple=e.maybe=e.Hex=e.Buffer=e.String=e.Boolean=e.Array=e.Number=e.Hash256bit=e.Hash160bit=e.Buffer256bit=e.isTaptree=e.isTapleaf=e.TAPLEAF_VERSION_MASK=e.Satoshi=e.isPoint=e.stacksEqual=e.typeforce=void 0;const t=un;e.typeforce=xE;const r=t.Buffer.alloc(32,0),n=t.Buffer.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex");function i(u,d){return u.length!==d.length?!1:u.every((y,p)=>y.equals(d[p]))}e.stacksEqual=i;function s(u){if(!t.Buffer.isBuffer(u)||u.length<33)return!1;const d=u[0],y=u.slice(1,33);if(y.compare(r)===0||y.compare(n)>=0)return!1;if((d===2||d===3)&&u.length===33)return!0;const p=u.slice(33);return p.compare(r)===0||p.compare(n)>=0?!1:d===4&&u.length===65}e.isPoint=s;const o=21*1e14;function a(u){return e.typeforce.UInt53(u)&&u<=o}e.Satoshi=a,e.TAPLEAF_VERSION_MASK=254;function c(u){return!u||!("output"in u)||!t.Buffer.isBuffer(u.output)?!1:u.version!==void 0?(u.version&e.TAPLEAF_VERSION_MASK)===u.version:!0}e.isTapleaf=c;function f(u){return(0,e.Array)(u)?u.length!==2?!1:u.every(d=>f(d)):c(u)}e.isTaptree=f,e.Buffer256bit=e.typeforce.BufferN(32),e.Hash160bit=e.typeforce.BufferN(20),e.Hash256bit=e.typeforce.BufferN(32),e.Number=e.typeforce.Number,e.Array=e.typeforce.Array,e.Boolean=e.typeforce.Boolean,e.String=e.typeforce.String,e.Buffer=e.typeforce.Buffer,e.Hex=e.typeforce.Hex,e.maybe=e.typeforce.maybe,e.tuple=e.typeforce.tuple,e.UInt8=e.typeforce.UInt8,e.UInt32=e.typeforce.UInt32,e.Function=e.typeforce.Function,e.BufferN=e.typeforce.BufferN,e.Null=e.typeforce.Null,e.oneOf=e.typeforce.oneOf})(qe);var fs={},Le={};Object.defineProperty(Le,"__esModule",{value:!0});Le.BufferReader=Le.BufferWriter=Le.cloneBuffer=Le.reverseBuffer=Le.writeUInt64LE=Le.readUInt64LE=Le.varuint=void 0;const Gr=qe,{typeforce:D0}=Gr,Zi=Kl;Le.varuint=Zi;function j0(e,t){if(typeof e!="number")throw new Error("cannot write a non-number as a number");if(e<0)throw new Error("specified a negative value for writing an unsigned value");if(e>t)throw new Error("RangeError: value out of range");if(Math.floor(e)!==e)throw new Error("value has a fractional component")}function z0(e,t){const r=e.readUInt32LE(t);let n=e.readUInt32LE(t+4);return n*=4294967296,j0(n+r,9007199254740991),n+r}Le.readUInt64LE=z0;function q0(e,t,r){return j0(t,9007199254740991),e.writeInt32LE(t&-1,r),e.writeUInt32LE(Math.floor(t/4294967296),r+4),r+8}Le.writeUInt64LE=q0;function AE(e){if(e.length<1)return e;let t=e.length-1,r=0;for(let n=0;n<e.length/2;n++)r=e[n],e[n]=e[t],e[t]=r,t--;return e}Le.reverseBuffer=AE;function _E(e){const t=Buffer.allocUnsafe(e.length);return e.copy(t),t}Le.cloneBuffer=_E;class of{static withCapacity(t){return new of(Buffer.alloc(t))}constructor(t,r=0){this.buffer=t,this.offset=r,D0(Gr.tuple(Gr.Buffer,Gr.UInt32),[t,r])}writeUInt8(t){this.offset=this.buffer.writeUInt8(t,this.offset)}writeInt32(t){this.offset=this.buffer.writeInt32LE(t,this.offset)}writeUInt32(t){this.offset=this.buffer.writeUInt32LE(t,this.offset)}writeUInt64(t){this.offset=q0(this.buffer,t,this.offset)}writeVarInt(t){Zi.encode(t,this.buffer,this.offset),this.offset+=Zi.encode.bytes}writeSlice(t){if(this.buffer.length<this.offset+t.length)throw new Error("Cannot write slice out of bounds");this.offset+=t.copy(this.buffer,this.offset)}writeVarSlice(t){this.writeVarInt(t.length),this.writeSlice(t)}writeVector(t){this.writeVarInt(t.length),t.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}`)}}Le.BufferWriter=of;class SE{constructor(t,r=0){this.buffer=t,this.offset=r,D0(Gr.tuple(Gr.Buffer,Gr.UInt32),[t,r])}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=z0(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const t=Zi.decode(this.buffer,this.offset);return this.offset+=Zi.decode.bytes,t}readSlice(t){if(this.buffer.length<this.offset+t)throw new Error("Cannot read slice out of bounds");const r=this.buffer.slice(this.offset,this.offset+t);return this.offset+=t,r}readVarSlice(){return this.readSlice(this.readVarInt())}readVector(){const t=this.readVarInt(),r=[];for(let n=0;n<t;n++)r.push(this.readVarSlice());return r}}Le.BufferReader=SE;var Nr={};const PE=N0(e2);var Ln={},rt={},Qe={},af={},Po={};Object.defineProperty(Po,"__esModule",{value:!0});Po.crypto=void 0;Po.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;(function(e){/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */Object.defineProperty(e,"__esModule",{value:!0}),e.wrapXOFConstructorWithOpts=e.wrapConstructorWithOpts=e.wrapConstructor=e.Hash=e.nextTick=e.swap32IfBE=e.byteSwapIfBE=e.swap8IfBE=e.isLE=void 0,e.isBytes=r,e.anumber=n,e.abytes=i,e.ahash=s,e.aexists=o,e.aoutput=a,e.u8=c,e.u32=f,e.clean=u,e.createView=d,e.rotr=y,e.rotl=p,e.byteSwap=g,e.byteSwap32=b,e.bytesToHex=P,e.hexToBytes=T,e.asyncLoop=R,e.utf8ToBytes=L,e.bytesToUtf8=S,e.toBytes=$,e.kdfInputToBytes=C,e.concatBytes=U,e.checkOpts=j,e.createHasher=Y,e.createOptHasher=X,e.createXOFer=J,e.randomBytes=M;const t=Po;function r(B){return B instanceof Uint8Array||ArrayBuffer.isView(B)&&B.constructor.name==="Uint8Array"}function n(B){if(!Number.isSafeInteger(B)||B<0)throw new Error("positive integer expected, got "+B)}function i(B,...q){if(!r(B))throw new Error("Uint8Array expected");if(q.length>0&&!q.includes(B.length))throw new Error("Uint8Array expected of length "+q+", got length="+B.length)}function s(B){if(typeof B!="function"||typeof B.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");n(B.outputLen),n(B.blockLen)}function o(B,q=!0){if(B.destroyed)throw new Error("Hash instance has been destroyed");if(q&&B.finished)throw new Error("Hash#digest() has already been called")}function a(B,q){i(B);const W=q.outputLen;if(B.length<W)throw new Error("digestInto() expects output buffer of length at least "+W)}function c(B){return new Uint8Array(B.buffer,B.byteOffset,B.byteLength)}function f(B){return new Uint32Array(B.buffer,B.byteOffset,Math.floor(B.byteLength/4))}function u(...B){for(let q=0;q<B.length;q++)B[q].fill(0)}function d(B){return new DataView(B.buffer,B.byteOffset,B.byteLength)}function y(B,q){return B<<32-q|B>>>q}function p(B,q){return B<<q|B>>>32-q>>>0}e.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function g(B){return B<<24&4278190080|B<<8&16711680|B>>>8&65280|B>>>24&255}e.swap8IfBE=e.isLE?B=>B:B=>g(B),e.byteSwapIfBE=e.swap8IfBE;function b(B){for(let q=0;q<B.length;q++)B[q]=g(B[q]);return B}e.swap32IfBE=e.isLE?B=>B:b;const E=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",A=Array.from({length:256},(B,q)=>q.toString(16).padStart(2,"0"));function P(B){if(i(B),E)return B.toHex();let q="";for(let W=0;W<B.length;W++)q+=A[B[W]];return q}const w={_0:48,_9:57,A:65,F:70,a:97,f:102};function _(B){if(B>=w._0&&B<=w._9)return B-w._0;if(B>=w.A&&B<=w.F)return B-(w.A-10);if(B>=w.a&&B<=w.f)return B-(w.a-10)}function T(B){if(typeof B!="string")throw new Error("hex string expected, got "+typeof B);if(E)return Uint8Array.fromHex(B);const q=B.length,W=q/2;if(q%2)throw new Error("hex string expected, got unpadded hex of length "+q);const k=new Uint8Array(W);for(let N=0,H=0;N<W;N++,H+=2){const Z=_(B.charCodeAt(H)),Q=_(B.charCodeAt(H+1));if(Z===void 0||Q===void 0){const ie=B[H]+B[H+1];throw new Error('hex string expected, got non-hex character "'+ie+'" at index '+H)}k[N]=Z*16+Q}return k}const I=async()=>{};e.nextTick=I;async function R(B,q,W){let k=Date.now();for(let N=0;N<B;N++){W(N);const H=Date.now()-k;H>=0&&H<q||(await(0,e.nextTick)(),k+=H)}}function L(B){if(typeof B!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(B))}function S(B){return new TextDecoder().decode(B)}function $(B){return typeof B=="string"&&(B=L(B)),i(B),B}function C(B){return typeof B=="string"&&(B=L(B)),i(B),B}function U(...B){let q=0;for(let k=0;k<B.length;k++){const N=B[k];i(N),q+=N.length}const W=new Uint8Array(q);for(let k=0,N=0;k<B.length;k++){const H=B[k];W.set(H,N),N+=H.length}return W}function j(B,q){if(q!==void 0&&{}.toString.call(q)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(B,q)}class V{}e.Hash=V;function Y(B){const q=k=>B().update($(k)).digest(),W=B();return q.outputLen=W.outputLen,q.blockLen=W.blockLen,q.create=()=>B(),q}function X(B){const q=(k,N)=>B(N).update($(k)).digest(),W=B({});return q.outputLen=W.outputLen,q.blockLen=W.blockLen,q.create=k=>B(k),q}function J(B){const q=(k,N)=>B(N).update($(k)).digest(),W=B({});return q.outputLen=W.outputLen,q.blockLen=W.blockLen,q.create=k=>B(k),q}e.wrapConstructor=Y,e.wrapConstructorWithOpts=X,e.wrapXOFConstructorWithOpts=J;function M(B=32){if(t.crypto&&typeof t.crypto.getRandomValues=="function")return t.crypto.getRandomValues(new Uint8Array(B));if(t.crypto&&typeof t.crypto.randomBytes=="function")return Uint8Array.from(t.crypto.randomBytes(B));throw new Error("crypto.getRandomValues must be defined")}})(af);Object.defineProperty(Qe,"__esModule",{value:!0});Qe.SHA512_IV=Qe.SHA384_IV=Qe.SHA224_IV=Qe.SHA256_IV=Qe.HashMD=void 0;Qe.setBigUint64=G0;Qe.Chi=TE;Qe.Maj=IE;const Ut=af;function G0(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),c=n?4:0,f=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+f,a,n)}function TE(e,t,r){return e&t^~e&r}function IE(e,t,r){return e&t^e&r^t&r}class kE extends Ut.Hash{constructor(t,r,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(t),this.view=(0,Ut.createView)(this.buffer)}update(t){(0,Ut.aexists)(this),t=(0,Ut.toBytes)(t),(0,Ut.abytes)(t);const{view:r,buffer:n,blockLen:i}=this,s=t.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=(0,Ut.createView)(t);for(;i<=s-o;o+=i)this.process(c,o);continue}n.set(t.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){(0,Ut.aexists)(this),(0,Ut.aoutput)(t,this),this.finished=!0;const{buffer:r,view:n,blockLen:i,isLE:s}=this;let{pos:o}=this;r[o++]=128,(0,Ut.clean)(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(n,0),o=0);for(let d=o;d<i;d++)r[d]=0;G0(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=(0,Ut.createView)(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const f=c/4,u=this.get();if(f>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<f;d++)a.setUint32(4*d,u[d],s)}digest(){const{buffer:t,outputLen:r}=this;this.digestInto(t);const n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:r,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return t.destroyed=o,t.finished=s,t.length=i,t.pos=a,i%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}}Qe.HashMD=kE;Qe.SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);Qe.SHA224_IV=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);Qe.SHA384_IV=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]);Qe.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 Vr=Qe,Me=af,bn=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),wr=new Uint32Array(80);class V0 extends Vr.HashMD{constructor(){super(64,20,8,!1),this.A=bn[0]|0,this.B=bn[1]|0,this.C=bn[2]|0,this.D=bn[3]|0,this.E=bn[4]|0}get(){const{A:t,B:r,C:n,D:i,E:s}=this;return[t,r,n,i,s]}set(t,r,n,i,s){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0}process(t,r){for(let c=0;c<16;c++,r+=4)wr[c]=t.getUint32(r,!1);for(let c=16;c<80;c++)wr[c]=(0,Me.rotl)(wr[c-3]^wr[c-8]^wr[c-14]^wr[c-16],1);let{A:n,B:i,C:s,D:o,E:a}=this;for(let c=0;c<80;c++){let f,u;c<20?(f=(0,Vr.Chi)(i,s,o),u=1518500249):c<40?(f=i^s^o,u=1859775393):c<60?(f=(0,Vr.Maj)(i,s,o),u=2400959708):(f=i^s^o,u=3395469782);const d=(0,Me.rotl)(n,5)+f+a+u+wr[c]|0;a=o,o=s,s=(0,Me.rotl)(i,30),i=n,n=d}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,this.set(n,i,s,o,a)}roundClean(){(0,Me.clean)(wr)}destroy(){this.set(0,0,0,0,0),(0,Me.clean)(this.buffer)}}rt.SHA1=V0;rt.sha1=(0,Me.createHasher)(()=>new V0);const BE=Math.pow(2,32),OE=Array.from({length:64},(e,t)=>Math.floor(BE*Math.abs(Math.sin(t+1)))),_s=bn.slice(0,4),sa=new Uint32Array(16);class W0 extends Vr.HashMD{constructor(){super(64,16,8,!0),this.A=_s[0]|0,this.B=_s[1]|0,this.C=_s[2]|0,this.D=_s[3]|0}get(){const{A:t,B:r,C:n,D:i}=this;return[t,r,n,i]}set(t,r,n,i){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0}process(t,r){for(let a=0;a<16;a++,r+=4)sa[a]=t.getUint32(r,!0);let{A:n,B:i,C:s,D:o}=this;for(let a=0;a<64;a++){let c,f,u;a<16?(c=(0,Vr.Chi)(i,s,o),f=a,u=[7,12,17,22]):a<32?(c=(0,Vr.Chi)(o,i,s),f=(5*a+1)%16,u=[5,9,14,20]):a<48?(c=i^s^o,f=(3*a+5)%16,u=[4,11,16,23]):(c=s^(i|~o),f=7*a%16,u=[6,10,15,21]),c=c+n+OE[a]+sa[f],n=o,o=s,s=i,i=i+(0,Me.rotl)(c,u[a%4])}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,this.set(n,i,s,o)}roundClean(){(0,Me.clean)(sa)}destroy(){this.set(0,0,0,0),(0,Me.clean)(this.buffer)}}rt.MD5=W0;rt.md5=(0,Me.createHasher)(()=>new W0);const CE=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),K0=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),RE=K0.map(e=>(9*e+5)%16),Y0=(()=>{const r=[[K0],[RE]];for(let n=0;n<4;n++)for(let i of r)i.push(i[n].map(s=>CE[s]));return r})(),Z0=Y0[0],X0=Y0[1],J0=[[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(e=>Uint8Array.from(e)),NE=Z0.map((e,t)=>e.map(r=>J0[t][r])),FE=X0.map((e,t)=>e.map(r=>J0[t][r])),$E=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),UE=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function Ad(e,t,r,n){return e===0?t^r^n:e===1?t&r|~t&n:e===2?(t|~r)^n:e===3?t&n|r&~n:t^(r|~n)}const Ss=new Uint32Array(16);class Q0 extends Vr.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:t,h1:r,h2:n,h3:i,h4:s}=this;return[t,r,n,i,s]}set(t,r,n,i,s){this.h0=t|0,this.h1=r|0,this.h2=n|0,this.h3=i|0,this.h4=s|0}process(t,r){for(let p=0;p<16;p++,r+=4)Ss[p]=t.getUint32(r,!0);let n=this.h0|0,i=n,s=this.h1|0,o=s,a=this.h2|0,c=a,f=this.h3|0,u=f,d=this.h4|0,y=d;for(let p=0;p<5;p++){const g=4-p,b=$E[p],E=UE[p],A=Z0[p],P=X0[p],w=NE[p],_=FE[p];for(let T=0;T<16;T++){const I=(0,Me.rotl)(n+Ad(p,s,a,f)+Ss[A[T]]+b,w[T])+d|0;n=d,d=f,f=(0,Me.rotl)(a,10)|0,a=s,s=I}for(let T=0;T<16;T++){const I=(0,Me.rotl)(i+Ad(g,o,c,u)+Ss[P[T]]+E,_[T])+y|0;i=y,y=u,u=(0,Me.rotl)(c,10)|0,c=o,o=I}}this.set(this.h1+a+u|0,this.h2+f+y|0,this.h3+d+i|0,this.h4+n+o|0,this.h0+s+c|0)}roundClean(){(0,Me.clean)(Ss)}destroy(){this.destroyed=!0,(0,Me.clean)(this.buffer),this.set(0,0,0,0,0)}}rt.RIPEMD160=Q0;rt.ripemd160=(0,Me.createHasher)(()=>new Q0);Object.defineProperty(Ln,"__esModule",{value:!0});Ln.sha1=Ln.SHA1=void 0;const ey=rt;Ln.SHA1=ey.SHA1;Ln.sha1=ey.sha1;const ty=N0(Mb);(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.taggedHash=e.TAGGED_HASH_PREFIXES=e.TAGS=e.hash256=e.hash160=e.sha256=e.sha1=e.ripemd160=void 0;const t=PE,r=Ln,n=ty;function i(u){return Buffer.from((0,t.ripemd160)(Uint8Array.from(u)))}e.ripemd160=i;function s(u){return Buffer.from((0,r.sha1)(Uint8Array.from(u)))}e.sha1=s;function o(u){return Buffer.from((0,n.sha256)(Uint8Array.from(u)))}e.sha256=o;function a(u){return Buffer.from((0,t.ripemd160)((0,n.sha256)(Uint8Array.from(u))))}e.hash160=a;function c(u){return Buffer.from((0,n.sha256)((0,n.sha256)(Uint8Array.from(u))))}e.hash256=c,e.TAGS=["BIP0340/challenge","BIP0340/aux","BIP0340/nonce","TapLeaf","TapBranch","TapSighash","TapTweak","KeyAgg list","KeyAgg coefficient"],e.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 f(u,d){return o(Buffer.concat([e.TAGGED_HASH_PREFIXES[u],d]))}e.taggedHash=f})(Nr);var oa={},ar={};Object.defineProperty(ar,"__esModule",{value:!0});ar.encode=ar.decode=ar.check=void 0;function HE(e){if(e.length<8||e.length>72||e[0]!==48||e[1]!==e.length-2||e[2]!==2)return!1;const t=e[3];if(t===0||5+t>=e.length||e[4+t]!==2)return!1;const r=e[5+t];return!(r===0||6+t+r!==e.length||e[4]&128||t>1&&e[4]===0&&!(e[5]&128)||e[t+6]&128||r>1&&e[t+6]===0&&!(e[t+7]&128))}ar.check=HE;function LE(e){if(e.length<8)throw new Error("DER sequence length is too short");if(e.length>72)throw new Error("DER sequence length is too long");if(e[0]!==48)throw new Error("Expected DER sequence");if(e[1]!==e.length-2)throw new Error("DER sequence length is invalid");if(e[2]!==2)throw new Error("Expected DER integer");const t=e[3];if(t===0)throw new Error("R length is zero");if(5+t>=e.length)throw new Error("R length is too long");if(e[4+t]!==2)throw new Error("Expected DER integer (2)");const r=e[5+t];if(r===0)throw new Error("S length is zero");if(6+t+r!==e.length)throw new Error("S length is invalid");if(e[4]&128)throw new Error("R value is negative");if(t>1&&e[4]===0&&!(e[5]&128))throw new Error("R value excessively padded");if(e[t+6]&128)throw new Error("S value is negative");if(r>1&&e[t+6]===0&&!(e[t+7]&128))throw new Error("S value excessively padded");return{r:e.slice(4,4+t),s:e.slice(6+t)}}ar.decode=LE;function ME(e,t){const r=e.length,n=t.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(e[0]&128)throw new Error("R value is negative");if(t[0]&128)throw new Error("S value is negative");if(r>1&&e[0]===0&&!(e[1]&128))throw new Error("R value excessively padded");if(n>1&&t[0]===0&&!(t[1]&128))throw new Error("S value excessively padded");const i=Buffer.allocUnsafe(6+r+n);return i[0]=48,i[1]=i.length-2,i[2]=2,i[3]=e.length,e.copy(i,4),i[4+r]=2,i[5+r]=t.length,t.copy(i,6+r),i}ar.encode=ME;var rn={};Object.defineProperty(rn,"__esModule",{value:!0});rn.REVERSE_OPS=rn.OPS=void 0;const iu={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};rn.OPS=iu;const ry={};rn.REVERSE_OPS=ry;for(const e of Object.keys(iu)){const t=iu[e];ry[t]=e}var kr={};Object.defineProperty(kr,"__esModule",{value:!0});kr.decode=kr.encode=kr.encodingLength=void 0;const Sr=rn;function ny(e){return e<Sr.OPS.OP_PUSHDATA1?1:e<=255?2:e<=65535?3:5}kr.encodingLength=ny;function DE(e,t,r){const n=ny(t);return n===1?e.writeUInt8(t,r):n===2?(e.writeUInt8(Sr.OPS.OP_PUSHDATA1,r),e.writeUInt8(t,r+1)):n===3?(e.writeUInt8(Sr.OPS.OP_PUSHDATA2,r),e.writeUInt16LE(t,r+1)):(e.writeUInt8(Sr.OPS.OP_PUSHDATA4,r),e.writeUInt32LE(t,r+1)),n}kr.encode=DE;function jE(e,t){const r=e.readUInt8(t);let n,i;if(r<Sr.OPS.OP_PUSHDATA1)n=r,i=1;else if(r===Sr.OPS.OP_PUSHDATA1){if(t+2>e.length)return null;n=e.readUInt8(t+1),i=2}else if(r===Sr.OPS.OP_PUSHDATA2){if(t+3>e.length)return null;n=e.readUInt16LE(t+1),i=3}else{if(t+5>e.length)return null;if(r!==Sr.OPS.OP_PUSHDATA4)throw new Error("Unexpected opcode");n=e.readUInt32LE(t+1),i=5}return{opcode:r,number:n,size:i}}kr.decode=jE;var Mn={};Object.defineProperty(Mn,"__esModule",{value:!0});Mn.encode=Mn.decode=void 0;function zE(e,t,r){t=t||4,r=r===void 0?!0:r;const n=e.length;if(n===0)return 0;if(n>t)throw new TypeError("Script number overflow");if(r&&!(e[n-1]&127)&&(n<=1||!(e[n-2]&128)))throw new Error("Non-minimally encoded script number");if(n===5){const s=e.readUInt32LE(0),o=e.readUInt8(4);return o&128?-((o&-129)*4294967296+s):o*4294967296+s}let i=0;for(let s=0;s<n;++s)i|=e[s]<<8*s;return e[n-1]&128?-(i&~(128<<8*(n-1))):i}Mn.decode=zE;function qE(e){return e>2147483647?5:e>8388607?4:e>32767?3:e>127?2:e>0?1:0}function GE(e){let t=Math.abs(e);const r=qE(t),n=Buffer.allocUnsafe(r),i=e<0;for(let s=0;s<r;++s)n.writeUInt8(t&255,s),t>>=8;return n[r-1]&128?n.writeUInt8(i?128:0,r-1):i&&(n[r-1]|=128),n}Mn.encode=GE;var $r={},_d;function VE(){if(_d)return $r;_d=1,Object.defineProperty($r,"__esModule",{value:!0}),$r.encode=$r.decode=void 0;const e=ar,t=pt(),r=qe,{typeforce:n}=r,i=Buffer.alloc(1,0);function s(f){let u=0;for(;f[u]===0;)++u;return u===f.length?i:(f=f.slice(u),f[0]&128?Buffer.concat([i,f],1+f.length):f)}function o(f){f[0]===0&&(f=f.slice(1));const u=Buffer.alloc(32,0),d=Math.max(0,32-f.length);return f.copy(u,d),u}function a(f){const u=f.readUInt8(f.length-1);if(!(0,t.isDefinedHashType)(u))throw new Error("Invalid hashType "+u);const d=e.decode(f.slice(0,-1)),y=o(d.r),p=o(d.s);return{signature:Buffer.concat([y,p],64),hashType:u}}$r.decode=a;function c(f,u){if(n({signature:r.BufferN(64),hashType:r.UInt8},{signature:f,hashType:u}),!(0,t.isDefinedHashType)(u))throw new Error("Invalid hashType "+u);const d=Buffer.allocUnsafe(1);d.writeUInt8(u,0);const y=s(f.slice(0,32)),p=s(f.slice(32,64));return Buffer.concat([e.encode(y,p),d])}return $r.encode=c,$r}var Sd;function pt(){return Sd||(Sd=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.signature=e.number=e.isCanonicalScriptSignature=e.isDefinedHashType=e.isCanonicalPubKey=e.toStack=e.fromASM=e.toASM=e.decompile=e.compile=e.countNonPushOnlyOPs=e.isPushOnly=e.OPS=void 0;const t=ar,r=rn;Object.defineProperty(e,"OPS",{enumerable:!0,get:function(){return r.OPS}});const n=kr,i=Mn,s=VE(),o=qe,{typeforce:a}=o,c=r.OPS.OP_RESERVED;function f(S){return o.Number(S)&&(S===r.OPS.OP_0||S>=r.OPS.OP_1&&S<=r.OPS.OP_16||S===r.OPS.OP_1NEGATE)}function u(S){return o.Buffer(S)||f(S)}function d(S){return o.Array(S)&&S.every(u)}e.isPushOnly=d;function y(S){return S.length-S.filter(u).length}e.countNonPushOnlyOPs=y;function p(S){if(S.length===0)return r.OPS.OP_0;if(S.length===1){if(S[0]>=1&&S[0]<=16)return c+S[0];if(S[0]===129)return r.OPS.OP_1NEGATE}}function g(S){return Buffer.isBuffer(S)}function b(S){return o.Array(S)}function E(S){return Buffer.isBuffer(S)}function A(S){if(g(S))return S;a(o.Array,S);const $=S.reduce((j,V)=>E(V)?V.length===1&&p(V)!==void 0?j+1:j+n.encodingLength(V.length)+V.length:j+1,0),C=Buffer.allocUnsafe($);let U=0;if(S.forEach(j=>{if(E(j)){const V=p(j);if(V!==void 0){C.writeUInt8(V,U),U+=1;return}U+=n.encode(C,j.length,U),j.copy(C,U),U+=j.length}else C.writeUInt8(j,U),U+=1}),U!==C.length)throw new Error("Could not decode chunks");return C}e.compile=A;function P(S){if(b(S))return S;a(o.Buffer,S);const $=[];let C=0;for(;C<S.length;){const U=S[C];if(U>r.OPS.OP_0&&U<=r.OPS.OP_PUSHDATA4){const j=n.decode(S,C);if(j===null||(C+=j.size,C+j.number>S.length))return null;const V=S.slice(C,C+j.number);C+=j.number;const Y=p(V);Y!==void 0?$.push(Y):$.push(V)}else $.push(U),C+=1}return $}e.decompile=P;function w(S){if(g(S)&&(S=P(S)),!S)throw new Error("Could not convert invalid chunks to ASM");return S.map($=>{if(E($)){const C=p($);if(C===void 0)return $.toString("hex");$=C}return r.REVERSE_OPS[$]}).join(" ")}e.toASM=w;function _(S){return a(o.String,S),A(S.split(" ").map($=>r.OPS[$]!==void 0?r.OPS[$]:(a(o.Hex,$),Buffer.from($,"hex"))))}e.fromASM=_;function T(S){return S=P(S),a(d,S),S.map($=>E($)?$:$===r.OPS.OP_0?Buffer.allocUnsafe(0):i.encode($-c))}e.toStack=T;function I(S){return o.isPoint(S)}e.isCanonicalPubKey=I;function R(S){const $=S&-129;return $>0&&$<4}e.isDefinedHashType=R;function L(S){return!Buffer.isBuffer(S)||!R(S[S.length-1])?!1:t.check(S.slice(0,-1))}e.isCanonicalScriptSignature=L,e.number=i,e.signature=s}(oa)),oa}Object.defineProperty(fs,"__esModule",{value:!0});fs.Transaction=void 0;const Be=Le,We=Nr,Pd=pt(),WE=pt(),ue=qe,{typeforce:Ht}=ue;function Dt(e){const t=e.length;return Be.varuint.encodingLength(t)+t}function KE(e){const t=e.length;return Be.varuint.encodingLength(t)+e.reduce((r,n)=>r+Dt(n),0)}const _r=Buffer.allocUnsafe(0),aa=[],ca=Buffer.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),Td=Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),YE=Buffer.from("ffffffffffffffff","hex"),ZE={script:_r,valueBuffer:YE};function XE(e){return e.value!==void 0}class ae{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(t,r){const n=new Be.BufferReader(t),i=new ae;i.version=n.readInt32();const s=n.readUInt8(),o=n.readUInt8();let a=!1;s===ae.ADVANCED_TRANSACTION_MARKER&&o===ae.ADVANCED_TRANSACTION_FLAG?a=!0:n.offset-=2;const c=n.readVarInt();for(let u=0;u<c;++u)i.ins.push({hash:n.readSlice(32),index:n.readUInt32(),script:n.readVarSlice(),sequence:n.readUInt32(),witness:aa});const f=n.readVarInt();for(let u=0;u<f;++u)i.outs.push({value:n.readUInt64(),script:n.readVarSlice()});if(a){for(let u=0;u<c;++u)i.ins[u].witness=n.readVector();if(!i.hasWitnesses())throw new Error("Transaction has superfluous witness data")}if(i.locktime=n.readUInt32(),r)return i;if(n.offset!==t.length)throw new Error("Transaction has unexpected data");return i}static fromHex(t){return ae.fromBuffer(Buffer.from(t,"hex"),!1)}static isCoinbaseHash(t){Ht(ue.Hash256bit,t);for(let r=0;r<32;++r)if(t[r]!==0)return!1;return!0}isCoinbase(){return this.ins.length===1&&ae.isCoinbaseHash(this.ins[0].hash)}addInput(t,r,n,i){return Ht(ue.tuple(ue.Hash256bit,ue.UInt32,ue.maybe(ue.UInt32),ue.maybe(ue.Buffer)),arguments),ue.Null(n)&&(n=ae.DEFAULT_SEQUENCE),this.ins.push({hash:t,index:r,script:i||_r,sequence:n,witness:aa})-1}addOutput(t,r){return Ht(ue.tuple(ue.Buffer,ue.Satoshi),arguments),this.outs.push({script:t,value:r})-1}hasWitnesses(){return this.ins.some(t=>t.witness.length!==0)}stripWitnesses(){this.ins.forEach(t=>{t.witness=aa})}weight(){const t=this.byteLength(!1),r=this.byteLength(!0);return t*3+r}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(t=!0){const r=t&&this.hasWitnesses();return(r?10:8)+Be.varuint.encodingLength(this.ins.length)+Be.varuint.encodingLength(this.outs.length)+this.ins.reduce((n,i)=>n+40+Dt(i.script),0)+this.outs.reduce((n,i)=>n+8+Dt(i.script),0)+(r?this.ins.reduce((n,i)=>n+KE(i.witness),0):0)}clone(){const t=new ae;return t.version=this.version,t.locktime=this.locktime,t.ins=this.ins.map(r=>({hash:r.hash,index:r.index,script:r.script,sequence:r.sequence,witness:r.witness})),t.outs=this.outs.map(r=>({script:r.script,value:r.value})),t}hashForSignature(t,r,n){if(Ht(ue.tuple(ue.UInt32,ue.Buffer,ue.Number),arguments),t>=this.ins.length)return Td;const i=Pd.compile(Pd.decompile(r).filter(a=>a!==WE.OPS.OP_CODESEPARATOR)),s=this.clone();if((n&31)===ae.SIGHASH_NONE)s.outs=[],s.ins.forEach((a,c)=>{c!==t&&(a.sequence=0)});else if((n&31)===ae.SIGHASH_SINGLE){if(t>=this.outs.length)return Td;s.outs.length=t+1;for(let a=0;a<t;a++)s.outs[a]=ZE;s.ins.forEach((a,c)=>{c!==t&&(a.sequence=0)})}n&ae.SIGHASH_ANYONECANPAY?(s.ins=[s.ins[t]],s.ins[0].script=i):(s.ins.forEach(a=>{a.script=_r}),s.ins[t].script=i);const o=Buffer.allocUnsafe(s.byteLength(!1)+4);return o.writeInt32LE(n,o.length-4),s.__toBuffer(o,0,!1),We.hash256(o)}hashForWitnessV1(t,r,n,i,s,o){if(Ht(ue.tuple(ue.UInt32,Ht.arrayOf(ue.Buffer),Ht.arrayOf(ue.Satoshi),ue.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=i===ae.SIGHASH_DEFAULT?ae.SIGHASH_ALL:i&ae.SIGHASH_OUTPUT_MASK,f=(i&ae.SIGHASH_INPUT_MASK)===ae.SIGHASH_ANYONECANPAY,u=a===ae.SIGHASH_NONE,d=a===ae.SIGHASH_SINGLE;let y=_r,p=_r,g=_r,b=_r,E=_r;if(!f){let _=Be.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(T=>{_.writeSlice(T.hash),_.writeUInt32(T.index)}),y=We.sha256(_.end()),_=Be.BufferWriter.withCapacity(8*this.ins.length),n.forEach(T=>_.writeUInt64(T)),p=We.sha256(_.end()),_=Be.BufferWriter.withCapacity(r.map(Dt).reduce((T,I)=>T+I)),r.forEach(T=>_.writeVarSlice(T)),g=We.sha256(_.end()),_=Be.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(T=>_.writeUInt32(T.sequence)),b=We.sha256(_.end())}if(u||d){if(d&&t<this.outs.length){const _=this.outs[t],T=Be.BufferWriter.withCapacity(8+Dt(_.script));T.writeUInt64(_.value),T.writeVarSlice(_.script),E=We.sha256(T.end())}}else{const _=this.outs.map(I=>8+Dt(I.script)).reduce((I,R)=>I+R),T=Be.BufferWriter.withCapacity(_);this.outs.forEach(I=>{T.writeUInt64(I.value),T.writeVarSlice(I.script)}),E=We.sha256(T.end())}const A=(s?2:0)+(o?1:0),P=174-(f?49:0)-(u?32:0)+(o?32:0)+(s?37:0),w=Be.BufferWriter.withCapacity(P);if(w.writeUInt8(i),w.writeInt32(this.version),w.writeUInt32(this.locktime),w.writeSlice(y),w.writeSlice(p),w.writeSlice(g),w.writeSlice(b),u||d||w.writeSlice(E),w.writeUInt8(A),f){const _=this.ins[t];w.writeSlice(_.hash),w.writeUInt32(_.index),w.writeUInt64(n[t]),w.writeVarSlice(r[t]),w.writeUInt32(_.sequence)}else w.writeUInt32(t);if(o){const _=Be.BufferWriter.withCapacity(Dt(o));_.writeVarSlice(o),w.writeSlice(We.sha256(_.end()))}return d&&w.writeSlice(E),s&&(w.writeSlice(s),w.writeUInt8(0),w.writeUInt32(4294967295)),We.taggedHash("TapSighash",Buffer.concat([Buffer.from([0]),w.end()]))}hashForWitnessV0(t,r,n,i){Ht(ue.tuple(ue.UInt32,ue.Buffer,ue.Satoshi,ue.UInt32),arguments);let s=Buffer.from([]),o,a=ca,c=ca,f=ca;if(i&ae.SIGHASH_ANYONECANPAY||(s=Buffer.allocUnsafe(36*this.ins.length),o=new Be.BufferWriter(s,0),this.ins.forEach(d=>{o.writeSlice(d.hash),o.writeUInt32(d.index)}),c=We.hash256(s)),!(i&ae.SIGHASH_ANYONECANPAY)&&(i&31)!==ae.SIGHASH_SINGLE&&(i&31)!==ae.SIGHASH_NONE&&(s=Buffer.allocUnsafe(4*this.ins.length),o=new Be.BufferWriter(s,0),this.ins.forEach(d=>{o.writeUInt32(d.sequence)}),f=We.hash256(s)),(i&31)!==ae.SIGHASH_SINGLE&&(i&31)!==ae.SIGHASH_NONE){const d=this.outs.reduce((y,p)=>y+8+Dt(p.script),0);s=Buffer.allocUnsafe(d),o=new Be.BufferWriter(s,0),this.outs.forEach(y=>{o.writeUInt64(y.value),o.writeVarSlice(y.script)}),a=We.hash256(s)}else if((i&31)===ae.SIGHASH_SINGLE&&t<this.outs.length){const d=this.outs[t];s=Buffer.allocUnsafe(8+Dt(d.script)),o=new Be.BufferWriter(s,0),o.writeUInt64(d.value),o.writeVarSlice(d.script),a=We.hash256(s)}s=Buffer.allocUnsafe(156+Dt(r)),o=new Be.BufferWriter(s,0);const u=this.ins[t];return o.writeInt32(this.version),o.writeSlice(c),o.writeSlice(f),o.writeSlice(u.hash),o.writeUInt32(u.index),o.writeVarSlice(r),o.writeUInt64(n),o.writeUInt32(u.sequence),o.writeSlice(a),o.writeUInt32(this.locktime),o.writeUInt32(i),We.hash256(s)}getHash(t){return t&&this.isCoinbase()?Buffer.alloc(32,0):We.hash256(this.__toBuffer(void 0,void 0,t))}getId(){return(0,Be.reverseBuffer)(this.getHash(!1)).toString("hex")}toBuffer(t,r){return this.__toBuffer(t,r,!0)}toHex(){return this.toBuffer(void 0,void 0).toString("hex")}setInputScript(t,r){Ht(ue.tuple(ue.Number,ue.Buffer),arguments),this.ins[t].script=r}setWitness(t,r){Ht(ue.tuple(ue.Number,[ue.Buffer]),arguments),this.ins[t].witness=r}__toBuffer(t,r,n=!1){t||(t=Buffer.allocUnsafe(this.byteLength(n)));const i=new Be.BufferWriter(t,r||0);i.writeInt32(this.version);const s=n&&this.hasWitnesses();return s&&(i.writeUInt8(ae.ADVANCED_TRANSACTION_MARKER),i.writeUInt8(ae.ADVANCED_TRANSACTION_FLAG)),i.writeVarInt(this.ins.length),this.ins.forEach(o=>{i.writeSlice(o.hash),i.writeUInt32(o.index),i.writeVarSlice(o.script),i.writeUInt32(o.sequence)}),i.writeVarInt(this.outs.length),this.outs.forEach(o=>{XE(o)?i.writeUInt64(o.value):i.writeSlice(o.valueBuffer),i.writeVarSlice(o.script)}),s&&this.ins.forEach(o=>{i.writeVector(o.witness)}),i.writeUInt32(this.locktime),r!==void 0?t.slice(r,i.offset):t}}fs.Transaction=ae;ae.DEFAULT_SEQUENCE=4294967295;ae.SIGHASH_DEFAULT=0;ae.SIGHASH_ALL=1;ae.SIGHASH_NONE=2;ae.SIGHASH_SINGLE=3;ae.SIGHASH_ANYONECANPAY=128;ae.SIGHASH_OUTPUT_MASK=3;ae.SIGHASH_INPUT_MASK=128;ae.ADVANCED_TRANSACTION_MARKER=0;ae.ADVANCED_TRANSACTION_FLAG=1;var me={},ds={};Object.defineProperty(ds,"__esModule",{value:!0});const JE=9007199254740991;function cf(e){if(e<0||e>JE||e%1!==0)throw new RangeError("value out of range")}function li(e,t,r){if(cf(e),t||(t=Buffer.allocUnsafe(iy(e))),!Buffer.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");return r||(r=0),e<253?(t.writeUInt8(e,r),Object.assign(li,{bytes:1})):e<=65535?(t.writeUInt8(253,r),t.writeUInt16LE(e,r+1),Object.assign(li,{bytes:3})):e<=4294967295?(t.writeUInt8(254,r),t.writeUInt32LE(e,r+1),Object.assign(li,{bytes:5})):(t.writeUInt8(255,r),t.writeUInt32LE(e>>>0,r+1),t.writeUInt32LE(e/4294967296|0,r+5),Object.assign(li,{bytes:9})),t}ds.encode=li;function pi(e,t){if(!Buffer.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");t||(t=0);const r=e.readUInt8(t);if(r<253)return Object.assign(pi,{bytes:1}),r;if(r===253)return Object.assign(pi,{bytes:3}),e.readUInt16LE(t+1);if(r===254)return Object.assign(pi,{bytes:5}),e.readUInt32LE(t+1);{Object.assign(pi,{bytes:9});const n=e.readUInt32LE(t+1),s=e.readUInt32LE(t+5)*4294967296+n;return cf(s),s}}ds.decode=pi;function iy(e){return cf(e),e<253?1:e<=65535?3:e<=4294967295?5:9}ds.encodingLength=iy;var ua={},To={},ze={};Object.defineProperty(ze,"__esModule",{value:!0});ze.testnet=ze.regtest=ze.bitcoin=void 0;ze.bitcoin={messagePrefix:`Bitcoin Signed Message:
51
51
  `,bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128};ze.regtest={messagePrefix:`Bitcoin Signed Message:
52
52
  `,bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};ze.testnet={messagePrefix:`Bitcoin Signed Message:
53
- `,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var ut={};Object.defineProperty(ut,"__esModule",{value:!0});ut.value=ut.prop=void 0;function QE(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){const n=r.call(this);return this[t]=n,n},set(n){Object.defineProperty(this,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}})}ut.prop=QE;function e6(e){let t;return()=>(t!==void 0||(t=e()),t)}ut.value=e6;Object.defineProperty(To,"__esModule",{value:!0});To.p2data=void 0;const t6=ze,Ms=lt(),Lt=qe,Id=ut,kd=Ms.OPS;function r6(e,t){if(!e.data&&!e.output)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Lt.typeforce)({network:Lt.typeforce.maybe(Lt.typeforce.Object),output:Lt.typeforce.maybe(Lt.typeforce.Buffer),data:Lt.typeforce.maybe(Lt.typeforce.arrayOf(Lt.typeforce.Buffer))},e);const n={name:"embed",network:e.network||t6.bitcoin};if(Id.prop(n,"output",()=>{if(e.data)return Ms.compile([kd.OP_RETURN].concat(e.data))}),Id.prop(n,"data",()=>{if(e.output)return Ms.decompile(e.output).slice(1)}),t.validate&&e.output){const i=Ms.decompile(e.output);if(i[0]!==kd.OP_RETURN)throw new TypeError("Output is invalid");if(!i.slice(1).every(Lt.typeforce.Buffer))throw new TypeError("Output is invalid");if(e.data&&!(0,Lt.stacksEqual)(e.data,n.data))throw new TypeError("Data mismatch")}return Object.assign(n,e)}To.p2data=r6;var Io={};Object.defineProperty(Io,"__esModule",{value:!0});Io.p2ms=void 0;const n6=ze,wn=lt(),Ie=qe,vr=ut,vn=wn.OPS,Ps=vn.OP_RESERVED;function i6(e,t){if(!e.input&&!e.output&&!(e.pubkeys&&e.m!==void 0)&&!e.signatures)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{});function r(c){return wn.isCanonicalScriptSignature(c)||(t.allowIncomplete&&c===vn.OP_0)!==void 0}(0,Ie.typeforce)({network:Ie.typeforce.maybe(Ie.typeforce.Object),m:Ie.typeforce.maybe(Ie.typeforce.Number),n:Ie.typeforce.maybe(Ie.typeforce.Number),output:Ie.typeforce.maybe(Ie.typeforce.Buffer),pubkeys:Ie.typeforce.maybe(Ie.typeforce.arrayOf(Ie.isPoint)),signatures:Ie.typeforce.maybe(Ie.typeforce.arrayOf(r)),input:Ie.typeforce.maybe(Ie.typeforce.Buffer)},e);const i={network:e.network||n6.bitcoin};let s=[],o=!1;function a(c){o||(o=!0,s=wn.decompile(c),i.m=s[0]-Ps,i.n=s[s.length-2]-Ps,i.pubkeys=s.slice(1,-2))}if(vr.prop(i,"output",()=>{if(e.m&&i.n&&e.pubkeys)return wn.compile([].concat(Ps+e.m,e.pubkeys,Ps+i.n,vn.OP_CHECKMULTISIG))}),vr.prop(i,"m",()=>{if(i.output)return a(i.output),i.m}),vr.prop(i,"n",()=>{if(i.pubkeys)return i.pubkeys.length}),vr.prop(i,"pubkeys",()=>{if(e.output)return a(e.output),i.pubkeys}),vr.prop(i,"signatures",()=>{if(e.input)return wn.decompile(e.input).slice(1)}),vr.prop(i,"input",()=>{if(e.signatures)return wn.compile([vn.OP_0].concat(e.signatures))}),vr.prop(i,"witness",()=>{if(i.input)return[]}),vr.prop(i,"name",()=>{if(!(!i.m||!i.n))return`p2ms(${i.m} of ${i.n})`}),t.validate){if(e.output){if(a(e.output),!Ie.typeforce.Number(s[0]))throw new TypeError("Output is invalid");if(!Ie.typeforce.Number(s[s.length-2]))throw new TypeError("Output is invalid");if(s[s.length-1]!==vn.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(i.m<=0||i.n>16||i.m>i.n||i.n!==s.length-3)throw new TypeError("Output is invalid");if(!i.pubkeys.every(c=>(0,Ie.isPoint)(c)))throw new TypeError("Output is invalid");if(e.m!==void 0&&e.m!==i.m)throw new TypeError("m mismatch");if(e.n!==void 0&&e.n!==i.n)throw new TypeError("n mismatch");if(e.pubkeys&&!(0,Ie.stacksEqual)(e.pubkeys,i.pubkeys))throw new TypeError("Pubkeys mismatch")}if(e.pubkeys){if(e.n!==void 0&&e.n!==e.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(i.n=e.pubkeys.length,i.n<i.m)throw new TypeError("Pubkey count cannot be less than m")}if(e.signatures){if(e.signatures.length<i.m)throw new TypeError("Not enough signatures provided");if(e.signatures.length>i.m)throw new TypeError("Too many signatures provided")}if(e.input){if(e.input[0]!==vn.OP_0)throw new TypeError("Input is invalid");if(i.signatures.length===0||!i.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(e.signatures&&!(0,Ie.stacksEqual)(e.signatures,i.signatures))throw new TypeError("Signature mismatch");if(e.m!==void 0&&e.m!==e.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(i,e)}Io.p2ms=i6;var ko={};Object.defineProperty(ko,"__esModule",{value:!0});ko.p2pk=void 0;const s6=ze,En=lt(),_t=qe,gn=ut,Bd=En.OPS;function o6(e,t){if(!e.input&&!e.output&&!e.pubkey&&!e.input&&!e.signature)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,_t.typeforce)({network:_t.typeforce.maybe(_t.typeforce.Object),output:_t.typeforce.maybe(_t.typeforce.Buffer),pubkey:_t.typeforce.maybe(_t.isPoint),signature:_t.typeforce.maybe(En.isCanonicalScriptSignature),input:_t.typeforce.maybe(_t.typeforce.Buffer)},e);const r=gn.value(()=>En.decompile(e.input)),i={name:"p2pk",network:e.network||s6.bitcoin};if(gn.prop(i,"output",()=>{if(e.pubkey)return En.compile([e.pubkey,Bd.OP_CHECKSIG])}),gn.prop(i,"pubkey",()=>{if(e.output)return e.output.slice(1,-1)}),gn.prop(i,"signature",()=>{if(e.input)return r()[0]}),gn.prop(i,"input",()=>{if(e.signature)return En.compile([e.signature])}),gn.prop(i,"witness",()=>{if(i.input)return[]}),t.validate){if(e.output){if(e.output[e.output.length-1]!==Bd.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!(0,_t.isPoint)(i.pubkey))throw new TypeError("Output pubkey is invalid");if(e.pubkey&&!e.pubkey.equals(i.pubkey))throw new TypeError("Pubkey mismatch")}if(e.signature&&e.input&&!e.input.equals(i.input))throw new TypeError("Signature mismatch");if(e.input){if(r().length!==1)throw new TypeError("Input is invalid");if(!En.isCanonicalScriptSignature(i.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(i,e)}ko.p2pk=o6;var Bo={};function a6(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var n=0;n<e.length;n++){var i=e.charAt(n),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=n}var o=e.length,a=e.charAt(0),c=Math.log(o)/Math.log(256),f=Math.log(256)/Math.log(o);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,b=0,E=0,A=p.length;E!==A&&p[E]===0;)E++,g++;for(var P=(A-E)*f+1>>>0,w=new Uint8Array(P);E!==A;){for(var _=p[E],T=0,I=P-1;(_!==0||T<b)&&I!==-1;I--,T++)_+=256*w[I]>>>0,w[I]=_%o>>>0,_=_/o>>>0;if(_!==0)throw new Error("Non-zero carry");b=T,E++}for(var R=P-b;R!==P&&w[R]===0;)R++;for(var L=a.repeat(g);R<P;++R)L+=e.charAt(w[R]);return L}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;for(var g=0,b=0,E=0;p[g]===a;)b++,g++;for(var A=(p.length-g)*c+1>>>0,P=new Uint8Array(A);p[g];){var w=p.charCodeAt(g);if(w>255)return;var _=t[w];if(_===255)return;for(var T=0,I=A-1;(_!==0||T<E)&&I!==-1;I--,T++)_+=o*P[I]>>>0,P[I]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");E=T,g++}for(var R=A-E;R!==A&&P[R]===0;)R++;for(var L=new Uint8Array(b+(A-R)),S=b;R!==A;)L[S++]=P[R++];return L}function y(p){var g=d(p);if(g)return g;throw new Error("Non-base"+o+" character")}return{encode:u,decodeUnsafe:d,decode:y}}var c6=a6;const u6=c6,f6="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";var d6=u6(f6),fa=d6,l6=function(e){function t(s){var o=Uint8Array.from(s),a=e(o),c=o.length+4,f=new Uint8Array(c);return f.set(o,0),f.set(a.subarray(0,4),o.length),fa.encode(f,c)}function r(s){var o=s.slice(0,-4),a=s.slice(-4),c=e(o);if(!(a[0]^c[0]|a[1]^c[1]|a[2]^c[2]|a[3]^c[3]))return o}function n(s){var o=fa.decodeUnsafe(s);if(o)return r(o)}function i(s){var o=fa.decode(s),a=r(o);if(!a)throw new Error("Invalid checksum");return a}return{encode:t,decode:i,decodeUnsafe:n}},{sha256:Od}=ty,p6=l6;function h6(e){return Od(Od(e))}var uf=p6(h6);Object.defineProperty(Bo,"__esModule",{value:!0});Bo.p2pkh=void 0;const da=Nr,y6=ze,xn=lt(),Ke=qe,Qt=ut,Cd=uf,Er=xn.OPS;function m6(e,t){if(!e.address&&!e.hash&&!e.output&&!e.pubkey&&!e.input)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Ke.typeforce)({network:Ke.typeforce.maybe(Ke.typeforce.Object),address:Ke.typeforce.maybe(Ke.typeforce.String),hash:Ke.typeforce.maybe(Ke.typeforce.BufferN(20)),output:Ke.typeforce.maybe(Ke.typeforce.BufferN(25)),pubkey:Ke.typeforce.maybe(Ke.isPoint),signature:Ke.typeforce.maybe(xn.isCanonicalScriptSignature),input:Ke.typeforce.maybe(Ke.typeforce.Buffer)},e);const r=Qt.value(()=>{const o=Buffer.from(Cd.decode(e.address)),a=o.readUInt8(0),c=o.slice(1);return{version:a,hash:c}}),n=Qt.value(()=>xn.decompile(e.input)),i=e.network||y6.bitcoin,s={name:"p2pkh",network:i};if(Qt.prop(s,"address",()=>{if(!s.hash)return;const o=Buffer.allocUnsafe(21);return o.writeUInt8(i.pubKeyHash,0),s.hash.copy(o,1),Cd.encode(o)}),Qt.prop(s,"hash",()=>{if(e.output)return e.output.slice(3,23);if(e.address)return r().hash;if(e.pubkey||s.pubkey)return da.hash160(e.pubkey||s.pubkey)}),Qt.prop(s,"output",()=>{if(s.hash)return xn.compile([Er.OP_DUP,Er.OP_HASH160,s.hash,Er.OP_EQUALVERIFY,Er.OP_CHECKSIG])}),Qt.prop(s,"pubkey",()=>{if(e.input)return n()[1]}),Qt.prop(s,"signature",()=>{if(e.input)return n()[0]}),Qt.prop(s,"input",()=>{if(e.pubkey&&e.signature)return xn.compile([e.signature,e.pubkey])}),Qt.prop(s,"witness",()=>{if(s.input)return[]}),t.validate){let o=Buffer.from([]);if(e.address){if(r().version!==i.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(r().hash.length!==20)throw new TypeError("Invalid address");o=r().hash}if(e.hash){if(o.length>0&&!o.equals(e.hash))throw new TypeError("Hash mismatch");o=e.hash}if(e.output){if(e.output.length!==25||e.output[0]!==Er.OP_DUP||e.output[1]!==Er.OP_HASH160||e.output[2]!==20||e.output[23]!==Er.OP_EQUALVERIFY||e.output[24]!==Er.OP_CHECKSIG)throw new TypeError("Output is invalid");const a=e.output.slice(3,23);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(e.pubkey){const a=da.hash160(e.pubkey);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(e.input){const a=n();if(a.length!==2)throw new TypeError("Input is invalid");if(!xn.isCanonicalScriptSignature(a[0]))throw new TypeError("Input has invalid signature");if(!(0,Ke.isPoint)(a[1]))throw new TypeError("Input has invalid pubkey");if(e.signature&&!e.signature.equals(a[0]))throw new TypeError("Signature mismatch");if(e.pubkey&&!e.pubkey.equals(a[1]))throw new TypeError("Pubkey mismatch");const c=da.hash160(a[1]);if(o.length>0&&!o.equals(c))throw new TypeError("Hash mismatch")}}return Object.assign(s,e)}Bo.p2pkh=m6;var Oo={};Object.defineProperty(Oo,"__esModule",{value:!0});Oo.p2sh=void 0;const Rd=Nr,g6=ze,jt=lt(),be=qe,Mt=ut,Nd=uf,si=jt.OPS;function b6(e,t){if(!e.address&&!e.hash&&!e.output&&!e.redeem&&!e.input)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,be.typeforce)({network:be.typeforce.maybe(be.typeforce.Object),address:be.typeforce.maybe(be.typeforce.String),hash:be.typeforce.maybe(be.typeforce.BufferN(20)),output:be.typeforce.maybe(be.typeforce.BufferN(23)),redeem:be.typeforce.maybe({network:be.typeforce.maybe(be.typeforce.Object),output:be.typeforce.maybe(be.typeforce.Buffer),input:be.typeforce.maybe(be.typeforce.Buffer),witness:be.typeforce.maybe(be.typeforce.arrayOf(be.typeforce.Buffer))}),input:be.typeforce.maybe(be.typeforce.Buffer),witness:be.typeforce.maybe(be.typeforce.arrayOf(be.typeforce.Buffer))},e);let r=e.network;r||(r=e.redeem&&e.redeem.network||g6.bitcoin);const n={network:r},i=Mt.value(()=>{const a=Buffer.from(Nd.decode(e.address)),c=a.readUInt8(0),f=a.slice(1);return{version:c,hash:f}}),s=Mt.value(()=>jt.decompile(e.input)),o=Mt.value(()=>{const a=s(),c=a[a.length-1];return{network:r,output:c===si.OP_FALSE?Buffer.from([]):c,input:jt.compile(a.slice(0,-1)),witness:e.witness||[]}});if(Mt.prop(n,"address",()=>{if(!n.hash)return;const a=Buffer.allocUnsafe(21);return a.writeUInt8(n.network.scriptHash,0),n.hash.copy(a,1),Nd.encode(a)}),Mt.prop(n,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return i().hash;if(n.redeem&&n.redeem.output)return Rd.hash160(n.redeem.output)}),Mt.prop(n,"output",()=>{if(n.hash)return jt.compile([si.OP_HASH160,n.hash,si.OP_EQUAL])}),Mt.prop(n,"redeem",()=>{if(e.input)return o()}),Mt.prop(n,"input",()=>{if(!(!e.redeem||!e.redeem.input||!e.redeem.output))return jt.compile([].concat(jt.decompile(e.redeem.input),e.redeem.output))}),Mt.prop(n,"witness",()=>{if(n.redeem&&n.redeem.witness)return n.redeem.witness;if(n.input)return[]}),Mt.prop(n,"name",()=>{const a=["p2sh"];return n.redeem!==void 0&&n.redeem.name!==void 0&&a.push(n.redeem.name),a.join("-")}),t.validate){let a=Buffer.from([]);if(e.address){if(i().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(i().hash.length!==20)throw new TypeError("Invalid address");a=i().hash}if(e.hash){if(a.length>0&&!a.equals(e.hash))throw new TypeError("Hash mismatch");a=e.hash}if(e.output){if(e.output.length!==23||e.output[0]!==si.OP_HASH160||e.output[1]!==20||e.output[22]!==si.OP_EQUAL)throw new TypeError("Output is invalid");const f=e.output.slice(2,22);if(a.length>0&&!a.equals(f))throw new TypeError("Hash mismatch");a=f}const c=f=>{if(f.output){const u=jt.decompile(f.output);if(!u||u.length<1)throw new TypeError("Redeem.output too short");if(f.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(jt.countNonPushOnlyOPs(u)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const d=Rd.hash160(f.output);if(a.length>0&&!a.equals(d))throw new TypeError("Hash mismatch");a=d}if(f.input){const u=f.input.length>0,d=f.witness&&f.witness.length>0;if(!u&&!d)throw new TypeError("Empty input");if(u&&d)throw new TypeError("Input and witness provided");if(u){const y=jt.decompile(f.input);if(!jt.isPushOnly(y))throw new TypeError("Non push-only scriptSig")}}};if(e.input){const f=s();if(!f||f.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(o().output))throw new TypeError("Input is invalid");c(o())}if(e.redeem){if(e.redeem.network&&e.redeem.network!==r)throw new TypeError("Network mismatch");if(e.input){const f=o();if(e.redeem.output&&!e.redeem.output.equals(f.output))throw new TypeError("Redeem.output mismatch");if(e.redeem.input&&!e.redeem.input.equals(f.input))throw new TypeError("Redeem.input mismatch")}c(e.redeem)}if(e.witness&&e.redeem&&e.redeem.witness&&!(0,be.stacksEqual)(e.redeem.witness,e.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,e)}Oo.p2sh=b6;var Co={},dr={};Object.defineProperty(dr,"__esModule",{value:!0});dr.bech32m=dr.bech32=void 0;const Zs="qpzry9x8gf2tvdw0s3jn54khce6mua7l",sy={};for(let e=0;e<Zs.length;e++){const t=Zs.charAt(e);sy[t]=e}function Bn(e){const t=e>>25;return(e&33554431)<<5^-(t>>0&1)&996825010^-(t>>1&1)&642813549^-(t>>2&1)&513874426^-(t>>3&1)&1027748829^-(t>>4&1)&705979059}function Fd(e){let t=1;for(let r=0;r<e.length;++r){const n=e.charCodeAt(r);if(n<33||n>126)return"Invalid prefix ("+e+")";t=Bn(t)^n>>5}t=Bn(t);for(let r=0;r<e.length;++r){const n=e.charCodeAt(r);t=Bn(t)^n&31}return t}function ff(e,t,r,n){let i=0,s=0;const o=(1<<r)-1,a=[];for(let c=0;c<e.length;++c)for(i=i<<t|e[c],s+=t;s>=r;)s-=r,a.push(i>>s&o);if(n)s>0&&a.push(i<<r-s&o);else{if(s>=t)return"Excess padding";if(i<<r-s&o)return"Non-zero padding"}return a}function w6(e){return ff(e,8,5,!0)}function v6(e){const t=ff(e,5,8,!1);if(Array.isArray(t))return t}function E6(e){const t=ff(e,5,8,!1);if(Array.isArray(t))return t;throw new Error(t)}function oy(e){let t;e==="bech32"?t=1:t=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 f=Fd(o);if(typeof f=="string")throw new Error(f);let u=o+"1";for(let d=0;d<a.length;++d){const y=a[d];if(y>>5)throw new Error("Non 5-bit word");f=Bn(f)^y,u+=Zs.charAt(y)}for(let d=0;d<6;++d)f=Bn(f);f^=t;for(let d=0;d<6;++d){const y=f>>(5-d)*5&31;u+=Zs.charAt(y)}return u}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(),f=o.toUpperCase();if(o!==c&&o!==f)return"Mixed-case string "+o;o=c;const u=o.lastIndexOf("1");if(u===-1)return"No separator character for "+o;if(u===0)return"Missing prefix for "+o;const d=o.slice(0,u),y=o.slice(u+1);if(y.length<6)return"Data too short";let p=Fd(d);if(typeof p=="string")return p;const g=[];for(let b=0;b<y.length;++b){const E=y.charAt(b),A=sy[E];if(A===void 0)return"Unknown character "+E;p=Bn(p)^A,!(b+6>=y.length)&&g.push(A)}return p!==t?"Invalid checksum for "+o:{prefix:d,words:g}}function i(o,a){const c=n(o,a);if(typeof c=="object")return c}function s(o,a){const c=n(o,a);if(typeof c=="object")return c;throw new Error(c)}return{decodeUnsafe:i,decode:s,encode:r,toWords:w6,fromWordsUnsafe:v6,fromWords:E6}}dr.bech32=oy("bech32");dr.bech32m=oy("bech32m");Object.defineProperty(Co,"__esModule",{value:!0});Co.p2wpkh=void 0;const la=Nr,x6=ze,Ds=lt(),Ne=qe,xr=ut,Ts=dr,$d=Ds.OPS,A6=Buffer.alloc(0);function _6(e,t){if(!e.address&&!e.hash&&!e.output&&!e.pubkey&&!e.witness)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Ne.typeforce)({address:Ne.typeforce.maybe(Ne.typeforce.String),hash:Ne.typeforce.maybe(Ne.typeforce.BufferN(20)),input:Ne.typeforce.maybe(Ne.typeforce.BufferN(0)),network:Ne.typeforce.maybe(Ne.typeforce.Object),output:Ne.typeforce.maybe(Ne.typeforce.BufferN(22)),pubkey:Ne.typeforce.maybe(Ne.isPoint),signature:Ne.typeforce.maybe(Ds.isCanonicalScriptSignature),witness:Ne.typeforce.maybe(Ne.typeforce.arrayOf(Ne.typeforce.Buffer))},e);const r=xr.value(()=>{const s=Ts.bech32.decode(e.address),o=s.words.shift(),a=Ts.bech32.fromWords(s.words);return{version:o,prefix:s.prefix,data:Buffer.from(a)}}),n=e.network||x6.bitcoin,i={name:"p2wpkh",network:n};if(xr.prop(i,"address",()=>{if(!i.hash)return;const s=Ts.bech32.toWords(i.hash);return s.unshift(0),Ts.bech32.encode(n.bech32,s)}),xr.prop(i,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return r().data;if(e.pubkey||i.pubkey)return la.hash160(e.pubkey||i.pubkey)}),xr.prop(i,"output",()=>{if(i.hash)return Ds.compile([$d.OP_0,i.hash])}),xr.prop(i,"pubkey",()=>{if(e.pubkey)return e.pubkey;if(e.witness)return e.witness[1]}),xr.prop(i,"signature",()=>{if(e.witness)return e.witness[0]}),xr.prop(i,"input",()=>{if(i.witness)return A6}),xr.prop(i,"witness",()=>{if(e.pubkey&&e.signature)return[e.signature,e.pubkey]}),t.validate){let s=Buffer.from([]);if(e.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");s=r().data}if(e.hash){if(s.length>0&&!s.equals(e.hash))throw new TypeError("Hash mismatch");s=e.hash}if(e.output){if(e.output.length!==22||e.output[0]!==$d.OP_0||e.output[1]!==20)throw new TypeError("Output is invalid");if(s.length>0&&!s.equals(e.output.slice(2)))throw new TypeError("Hash mismatch");s=e.output.slice(2)}if(e.pubkey){const o=la.hash160(e.pubkey);if(s.length>0&&!s.equals(o))throw new TypeError("Hash mismatch");if(s=o,!(0,Ne.isPoint)(e.pubkey)||e.pubkey.length!==33)throw new TypeError("Invalid pubkey for p2wpkh")}if(e.witness){if(e.witness.length!==2)throw new TypeError("Witness is invalid");if(!Ds.isCanonicalScriptSignature(e.witness[0]))throw new TypeError("Witness has invalid signature");if(!(0,Ne.isPoint)(e.witness[1])||e.witness[1].length!==33)throw new TypeError("Witness has invalid pubkey");if(e.signature&&!e.signature.equals(e.witness[0]))throw new TypeError("Signature mismatch");if(e.pubkey&&!e.pubkey.equals(e.witness[1]))throw new TypeError("Pubkey mismatch");const o=la.hash160(e.witness[1]);if(s.length>0&&!s.equals(o))throw new TypeError("Hash mismatch")}}return Object.assign(i,e)}Co.p2wpkh=_6;var Ro={};Object.defineProperty(Ro,"__esModule",{value:!0});Ro.p2wsh=void 0;const Ud=Nr,S6=ze,rr=lt(),ge=qe,er=ut,Is=dr,Hd=rr.OPS,pa=Buffer.alloc(0);function ks(e){return!!(Buffer.isBuffer(e)&&e.length===65&&e[0]===4&&(0,ge.isPoint)(e))}function P6(e,t){if(!e.address&&!e.hash&&!e.output&&!e.redeem&&!e.witness)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,ge.typeforce)({network:ge.typeforce.maybe(ge.typeforce.Object),address:ge.typeforce.maybe(ge.typeforce.String),hash:ge.typeforce.maybe(ge.typeforce.BufferN(32)),output:ge.typeforce.maybe(ge.typeforce.BufferN(34)),redeem:ge.typeforce.maybe({input:ge.typeforce.maybe(ge.typeforce.Buffer),network:ge.typeforce.maybe(ge.typeforce.Object),output:ge.typeforce.maybe(ge.typeforce.Buffer),witness:ge.typeforce.maybe(ge.typeforce.arrayOf(ge.typeforce.Buffer))}),input:ge.typeforce.maybe(ge.typeforce.BufferN(0)),witness:ge.typeforce.maybe(ge.typeforce.arrayOf(ge.typeforce.Buffer))},e);const r=er.value(()=>{const o=Is.bech32.decode(e.address),a=o.words.shift(),c=Is.bech32.fromWords(o.words);return{version:a,prefix:o.prefix,data:Buffer.from(c)}}),n=er.value(()=>rr.decompile(e.redeem.input));let i=e.network;i||(i=e.redeem&&e.redeem.network||S6.bitcoin);const s={network:i};if(er.prop(s,"address",()=>{if(!s.hash)return;const o=Is.bech32.toWords(s.hash);return o.unshift(0),Is.bech32.encode(i.bech32,o)}),er.prop(s,"hash",()=>{if(e.output)return e.output.slice(2);if(e.address)return r().data;if(s.redeem&&s.redeem.output)return Ud.sha256(s.redeem.output)}),er.prop(s,"output",()=>{if(s.hash)return rr.compile([Hd.OP_0,s.hash])}),er.prop(s,"redeem",()=>{if(e.witness)return{output:e.witness[e.witness.length-1],input:pa,witness:e.witness.slice(0,-1)}}),er.prop(s,"input",()=>{if(s.witness)return pa}),er.prop(s,"witness",()=>{if(e.redeem&&e.redeem.input&&e.redeem.input.length>0&&e.redeem.output&&e.redeem.output.length>0){const o=rr.toStack(n());return s.redeem=Object.assign({witness:o},e.redeem),s.redeem.input=pa,[].concat(o,e.redeem.output)}if(e.redeem&&e.redeem.output&&e.redeem.witness)return[].concat(e.redeem.witness,e.redeem.output)}),er.prop(s,"name",()=>{const o=["p2wsh"];return s.redeem!==void 0&&s.redeem.name!==void 0&&o.push(s.redeem.name),o.join("-")}),t.validate){let o=Buffer.from([]);if(e.address){if(r().prefix!==i.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(e.hash){if(o.length>0&&!o.equals(e.hash))throw new TypeError("Hash mismatch");o=e.hash}if(e.output){if(e.output.length!==34||e.output[0]!==Hd.OP_0||e.output[1]!==32)throw new TypeError("Output is invalid");const a=e.output.slice(2);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(e.redeem){if(e.redeem.network&&e.redeem.network!==i)throw new TypeError("Network mismatch");if(e.redeem.input&&e.redeem.input.length>0&&e.redeem.witness&&e.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(e.redeem.output){const a=rr.decompile(e.redeem.output);if(!a||a.length<1)throw new TypeError("Redeem.output is invalid");if(e.redeem.output.byteLength>3600)throw new TypeError("Redeem.output unspendable if larger than 3600 bytes");if(rr.countNonPushOnlyOPs(a)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const c=Ud.sha256(e.redeem.output);if(o.length>0&&!o.equals(c))throw new TypeError("Hash mismatch");o=c}if(e.redeem.input&&!rr.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(e.witness&&e.redeem.witness&&!(0,ge.stacksEqual)(e.witness,e.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(e.redeem.input&&n().some(ks)||e.redeem.output&&(rr.decompile(e.redeem.output)||[]).some(ks))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(e.witness&&e.witness.length>0){const a=e.witness[e.witness.length-1];if(e.redeem&&e.redeem.output&&!e.redeem.output.equals(a))throw new TypeError("Witness and redeem.output mismatch");if(e.witness.some(ks)||(rr.decompile(a)||[]).some(ks))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(s,e)}Ro.p2wsh=P6;var oi={},nn={};Object.defineProperty(nn,"__esModule",{value:!0});nn.getEccLib=nn.initEccLib=void 0;const wi={};function T6(e,t){e?e!==wi.eccLib&&(t!=null&&t.DANGER_DO_NOT_VERIFY_ECCLIB||k6(e),wi.eccLib=e):wi.eccLib=e}nn.initEccLib=T6;function I6(){if(!wi.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return wi.eccLib}nn.getEccLib=I6;const tr=e=>Buffer.from(e,"hex");function k6(e){ht(typeof e.isXOnlyPoint=="function"),ht(e.isXOnlyPoint(tr("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),ht(e.isXOnlyPoint(tr("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),ht(e.isXOnlyPoint(tr("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),ht(e.isXOnlyPoint(tr("0000000000000000000000000000000000000000000000000000000000000001"))),ht(!e.isXOnlyPoint(tr("0000000000000000000000000000000000000000000000000000000000000000"))),ht(!e.isXOnlyPoint(tr("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),ht(typeof e.xOnlyPointAddTweak=="function"),B6.forEach(t=>{const r=e.xOnlyPointAddTweak(tr(t.pubkey),tr(t.tweak));t.result===null?ht(r===null):(ht(r!==null),ht(r.parity===t.parity),ht(Buffer.from(r.xOnlyPubkey).equals(tr(t.result))))})}function ht(e){if(!e)throw new Error("ecc library invalid")}const B6=[{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 df={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.tweakKey=e.tapTweakHash=e.tapleafHash=e.findScriptPath=e.toHashTree=e.rootHashFromPath=e.MAX_TAPTREE_DEPTH=e.LEAF_VERSION_TAPSCRIPT=void 0;const t=un,r=nn,n=Nr,i=Le,s=qe;e.LEAF_VERSION_TAPSCRIPT=192,e.MAX_TAPTREE_DEPTH=128;const o=b=>"left"in b&&"right"in b;function a(b,E){if(b.length<33)throw new TypeError(`The control-block length is too small. Got ${b.length}, expected min 33.`);const A=(b.length-33)/32;let P=E;for(let w=0;w<A;w++){const _=b.slice(33+32*w,65+32*w);P.compare(_)<0?P=p(P,_):P=p(_,P)}return P}e.rootHashFromPath=a;function c(b){if((0,s.isTapleaf)(b))return{hash:u(b)};const E=[c(b[0]),c(b[1])];E.sort((w,_)=>w.hash.compare(_.hash));const[A,P]=E;return{hash:p(A.hash,P.hash),left:A,right:P}}e.toHashTree=c;function f(b,E){if(o(b)){const A=f(b.left,E);if(A!==void 0)return[...A,b.right.hash];const P=f(b.right,E);if(P!==void 0)return[...P,b.left.hash]}else if(b.hash.equals(E))return[]}e.findScriptPath=f;function u(b){const E=b.version||e.LEAF_VERSION_TAPSCRIPT;return n.taggedHash("TapLeaf",t.Buffer.concat([t.Buffer.from([E]),g(b.output)]))}e.tapleafHash=u;function d(b,E){return n.taggedHash("TapTweak",t.Buffer.concat(E?[b,E]:[b]))}e.tapTweakHash=d;function y(b,E){if(!t.Buffer.isBuffer(b)||b.length!==32||E&&E.length!==32)return null;const A=d(b,E),P=(0,r.getEccLib)().xOnlyPointAddTweak(b,A);return!P||P.xOnlyPubkey===null?null:{parity:P.parity,x:t.Buffer.from(P.xOnlyPubkey)}}e.tweakKey=y;function p(b,E){return n.taggedHash("TapBranch",t.Buffer.concat([b,E]))}function g(b){const E=i.varuint.encodingLength(b.length),A=t.Buffer.allocUnsafe(E);return i.varuint.encode(b.length,A),t.Buffer.concat([A,b])}})(df);var Ye={},Ld;function O6(){if(Ld)return Ye;Ld=1,Object.defineProperty(Ye,"__esModule",{value:!0}),Ye.toOutputScript=Ye.fromOutputScript=Ye.toBech32=Ye.toBase58Check=Ye.fromBech32=Ye.fromBase58Check=void 0;const e=ze,t=lf(),r=lt(),n=qe,i=dr,s=uf,o=40,a=2,c=16,f=2,u=80,d="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 y(w,_){const T=w.slice(2);if(T.length<a||T.length>o)throw new TypeError("Invalid program length for segwit address");const I=w[0]-u;if(I<f||I>c)throw new TypeError("Invalid version for segwit address");if(w[1]!==T.length)throw new TypeError("Invalid script for segwit address");return console.warn(d),E(T,I,_.bech32)}function p(w){const _=Buffer.from(s.decode(w));if(_.length<21)throw new TypeError(w+" is too short");if(_.length>21)throw new TypeError(w+" is too long");const T=_.readUInt8(0),I=_.slice(1);return{version:T,hash:I}}Ye.fromBase58Check=p;function g(w){let _,T;try{_=i.bech32.decode(w)}catch{}if(_){if(T=_.words[0],T!==0)throw new TypeError(w+" uses wrong encoding")}else if(_=i.bech32m.decode(w),T=_.words[0],T===0)throw new TypeError(w+" uses wrong encoding");const I=i.bech32.fromWords(_.words.slice(1));return{version:T,prefix:_.prefix,data:Buffer.from(I)}}Ye.fromBech32=g;function b(w,_){(0,n.typeforce)((0,n.tuple)(n.Hash160bit,n.UInt8),arguments);const T=Buffer.allocUnsafe(21);return T.writeUInt8(_,0),w.copy(T,1),s.encode(T)}Ye.toBase58Check=b;function E(w,_,T){const I=i.bech32.toWords(w);return I.unshift(_),_===0?i.bech32.encode(T,I):i.bech32m.encode(T,I)}Ye.toBech32=E;function A(w,_){_=_||e.bitcoin;try{return t.p2pkh({output:w,network:_}).address}catch{}try{return t.p2sh({output:w,network:_}).address}catch{}try{return t.p2wpkh({output:w,network:_}).address}catch{}try{return t.p2wsh({output:w,network:_}).address}catch{}try{return t.p2tr({output:w,network:_}).address}catch{}try{return y(w,_)}catch{}throw new Error(r.toASM(w)+" has no matching Address")}Ye.fromOutputScript=A;function P(w,_){_=_||e.bitcoin;let T,I;try{T=p(w)}catch{}if(T){if(T.version===_.pubKeyHash)return t.p2pkh({hash:T.hash}).output;if(T.version===_.scriptHash)return t.p2sh({hash:T.hash}).output}else{try{I=g(w)}catch{}if(I){if(I.prefix!==_.bech32)throw new Error(w+" has an invalid prefix");if(I.version===0){if(I.data.length===20)return t.p2wpkh({hash:I.data}).output;if(I.data.length===32)return t.p2wsh({hash:I.data}).output}else if(I.version===1){if(I.data.length===32)return t.p2tr({pubkey:I.data}).output}else if(I.version>=f&&I.version<=c&&I.data.length>=a&&I.data.length<=o)return console.warn(d),r.compile([I.version+u,I.data])}}throw new Error(w+" has no matching Script")}return Ye.toOutputScript=P,Ye}var Md;function C6(){if(Md)return oi;Md=1,Object.defineProperty(oi,"__esModule",{value:!0}),oi.p2tr=void 0;const e=un,t=ze,r=lt(),n=qe,i=nn,s=df,o=ut,a=dr,c=O6(),f=r.OPS,u=1,d=80;function y(p,g){if(!p.address&&!p.output&&!p.pubkey&&!p.internalPubkey&&!(p.witness&&p.witness.length>1))throw new TypeError("Not enough data");g=Object.assign({validate:!0},g||{}),(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)},p);const b=o.value(()=>(0,c.fromBech32)(p.address)),E=o.value(()=>{if(!(!p.witness||!p.witness.length))return p.witness.length>=2&&p.witness[p.witness.length-1][0]===d?p.witness.slice(0,-1):p.witness.slice()}),A=o.value(()=>{if(p.scriptTree)return(0,s.toHashTree)(p.scriptTree);if(p.hash)return{hash:p.hash}}),P=p.network||t.bitcoin,w={name:"p2tr",network:P};if(o.prop(w,"address",()=>{if(!w.pubkey)return;const _=a.bech32m.toWords(w.pubkey);return _.unshift(u),a.bech32m.encode(P.bech32,_)}),o.prop(w,"hash",()=>{const _=A();if(_)return _.hash;const T=E();if(T&&T.length>1){const I=T[T.length-1],R=I[0]&n.TAPLEAF_VERSION_MASK,L=T[T.length-2],S=(0,s.tapleafHash)({output:L,version:R});return(0,s.rootHashFromPath)(I,S)}return null}),o.prop(w,"output",()=>{if(w.pubkey)return r.compile([f.OP_1,w.pubkey])}),o.prop(w,"redeemVersion",()=>p.redeemVersion?p.redeemVersion:p.redeem&&p.redeem.redeemVersion!==void 0&&p.redeem.redeemVersion!==null?p.redeem.redeemVersion:s.LEAF_VERSION_TAPSCRIPT),o.prop(w,"redeem",()=>{const _=E();if(!(!_||_.length<2))return{output:_[_.length-2],witness:_.slice(0,-2),redeemVersion:_[_.length-1][0]&n.TAPLEAF_VERSION_MASK}}),o.prop(w,"pubkey",()=>{if(p.pubkey)return p.pubkey;if(p.output)return p.output.slice(2);if(p.address)return b().data;if(w.internalPubkey){const _=(0,s.tweakKey)(w.internalPubkey,w.hash);if(_)return _.x}}),o.prop(w,"internalPubkey",()=>{if(p.internalPubkey)return p.internalPubkey;const _=E();if(_&&_.length>1)return _[_.length-1].slice(1,33)}),o.prop(w,"signature",()=>{if(p.signature)return p.signature;const _=E();if(!(!_||_.length!==1))return _[0]}),o.prop(w,"witness",()=>{if(p.witness)return p.witness;const _=A();if(_&&p.redeem&&p.redeem.output&&p.internalPubkey){const T=(0,s.tapleafHash)({output:p.redeem.output,version:w.redeemVersion}),I=(0,s.findScriptPath)(_,T);if(!I)return;const R=(0,s.tweakKey)(p.internalPubkey,_.hash);if(!R)return;const L=e.Buffer.concat([e.Buffer.from([w.redeemVersion|R.parity]),p.internalPubkey].concat(I));return[p.redeem.output,L]}if(p.signature)return[p.signature]}),g.validate){let _=e.Buffer.from([]);if(p.address){if(P&&P.bech32!==b().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(b().version!==u)throw new TypeError("Invalid address version");if(b().data.length!==32)throw new TypeError("Invalid address data");_=b().data}if(p.pubkey){if(_.length>0&&!_.equals(p.pubkey))throw new TypeError("Pubkey mismatch");_=p.pubkey}if(p.output){if(p.output.length!==34||p.output[0]!==f.OP_1||p.output[1]!==32)throw new TypeError("Output is invalid");if(_.length>0&&!_.equals(p.output.slice(2)))throw new TypeError("Pubkey mismatch");_=p.output.slice(2)}if(p.internalPubkey){const R=(0,s.tweakKey)(p.internalPubkey,w.hash);if(_.length>0&&!_.equals(R.x))throw new TypeError("Pubkey mismatch");_=R.x}if(_&&_.length&&!(0,i.getEccLib)().isXOnlyPoint(_))throw new TypeError("Invalid pubkey for p2tr");const T=A();if(p.hash&&T&&!p.hash.equals(T.hash))throw new TypeError("Hash mismatch");if(p.redeem&&p.redeem.output&&T){const R=(0,s.tapleafHash)({output:p.redeem.output,version:w.redeemVersion});if(!(0,s.findScriptPath)(T,R))throw new TypeError("Redeem script not in tree")}const I=E();if(p.redeem&&w.redeem){if(p.redeem.redeemVersion&&p.redeem.redeemVersion!==w.redeem.redeemVersion)throw new TypeError("Redeem.redeemVersion and witness mismatch");if(p.redeem.output){if(r.decompile(p.redeem.output).length===0)throw new TypeError("Redeem.output is invalid");if(w.redeem.output&&!p.redeem.output.equals(w.redeem.output))throw new TypeError("Redeem.output and witness mismatch")}if(p.redeem.witness&&w.redeem.witness&&!(0,n.stacksEqual)(p.redeem.witness,w.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(I&&I.length)if(I.length===1){if(p.signature&&!p.signature.equals(I[0]))throw new TypeError("Signature mismatch")}else{const R=I[I.length-1];if(R.length<33)throw new TypeError(`The control-block length is too small. Got ${R.length}, expected min 33.`);if((R.length-33)%32!==0)throw new TypeError(`The control-block length of ${R.length} is incorrect!`);const L=(R.length-33)/32;if(L>128)throw new TypeError(`The script path is too long. Got ${L}, expected max 128.`);const S=R.slice(1,33);if(p.internalPubkey&&!p.internalPubkey.equals(S))throw new TypeError("Internal pubkey mismatch");if(!(0,i.getEccLib)().isXOnlyPoint(S))throw new TypeError("Invalid internalPubkey for p2tr witness");const $=R[0]&n.TAPLEAF_VERSION_MASK,C=I[I.length-2],U=(0,s.tapleafHash)({output:C,version:$}),j=(0,s.rootHashFromPath)(R,U),V=(0,s.tweakKey)(S,j);if(!V)throw new TypeError("Invalid outputKey for p2tr witness");if(_.length&&!_.equals(V.x))throw new TypeError("Pubkey mismatch for p2tr witness");if(V.parity!==(R[0]&1))throw new Error("Incorrect parity")}}return Object.assign(w,p)}return oi.p2tr=y,oi}var Dd;function lf(){return Dd||(Dd=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.p2tr=e.p2wsh=e.p2wpkh=e.p2sh=e.p2pkh=e.p2pk=e.p2ms=e.embed=void 0;const t=To;Object.defineProperty(e,"embed",{enumerable:!0,get:function(){return t.p2data}});const r=Io;Object.defineProperty(e,"p2ms",{enumerable:!0,get:function(){return r.p2ms}});const n=ko;Object.defineProperty(e,"p2pk",{enumerable:!0,get:function(){return n.p2pk}});const i=Bo;Object.defineProperty(e,"p2pkh",{enumerable:!0,get:function(){return i.p2pkh}});const s=Oo;Object.defineProperty(e,"p2sh",{enumerable:!0,get:function(){return s.p2sh}});const o=Co;Object.defineProperty(e,"p2wpkh",{enumerable:!0,get:function(){return o.p2wpkh}});const a=Ro;Object.defineProperty(e,"p2wsh",{enumerable:!0,get:function(){return a.p2wsh}});const c=C6();Object.defineProperty(e,"p2tr",{enumerable:!0,get:function(){return c.p2tr}})}(ua)),ua}Object.defineProperty(me,"__esModule",{value:!0});me.signatureBlocksAction=me.checkInputForSig=me.pubkeyInScript=me.pubkeyPositionInScript=me.witnessStackToScriptWitness=me.isP2TR=me.isP2SHScript=me.isP2WSHScript=me.isP2WPKH=me.isP2PKH=me.isP2PK=me.isP2MS=void 0;const jd=ds,vi=lt(),Bs=fs,R6=Nr,fn=lf();function dn(e){return t=>{try{return e({output:t}),!0}catch{return!1}}}me.isP2MS=dn(fn.p2ms);me.isP2PK=dn(fn.p2pk);me.isP2PKH=dn(fn.p2pkh);me.isP2WPKH=dn(fn.p2wpkh);me.isP2WSHScript=dn(fn.p2wsh);me.isP2SHScript=dn(fn.p2sh);me.isP2TR=dn(fn.p2tr);function N6(e){let t=Buffer.allocUnsafe(0);function r(o){t=Buffer.concat([t,Buffer.from(o)])}function n(o){const a=t.length,c=jd.encodingLength(o);t=Buffer.concat([t,Buffer.allocUnsafe(c)]),jd.encode(o,t,a)}function i(o){n(o.length),r(o)}function s(o){n(o.length),o.forEach(i)}return s(e),t}me.witnessStackToScriptWitness=N6;function ay(e,t){const r=(0,R6.hash160)(e),n=e.slice(1,33),i=vi.decompile(t);if(i===null)throw new Error("Unknown script error");return i.findIndex(s=>typeof s=="number"?!1:s.equals(e)||s.equals(r)||s.equals(n))}me.pubkeyPositionInScript=ay;function F6(e,t){return ay(e,t)!==-1}me.pubkeyInScript=F6;function $6(e,t){return U6(e).some(n=>cy(n,vi.signature.decode,t))}me.checkInputForSig=$6;function cy(e,t,r){const{hashType:n}=t(e),i=[];switch(n&Bs.Transaction.SIGHASH_ANYONECANPAY&&i.push("addInput"),n&31){case Bs.Transaction.SIGHASH_ALL:break;case Bs.Transaction.SIGHASH_SINGLE:case Bs.Transaction.SIGHASH_NONE:i.push("addOutput"),i.push("setInputSequence");break}return i.indexOf(r)===-1}me.signatureBlocksAction=cy;function U6(e){let t=[];if((e.partialSig||[]).length===0){if(!e.finalScriptSig&&!e.finalScriptWitness)return[];t=H6(e)}else t=e.partialSig;return t.map(r=>r.signature)}function H6(e){const t=e.finalScriptSig?vi.decompile(e.finalScriptSig)||[]:[],r=e.finalScriptWitness?vi.decompile(e.finalScriptWitness)||[]:[];return t.concat(r).filter(n=>Buffer.isBuffer(n)&&vi.isCanonicalScriptSignature(n)).map(n=>({signature:n}))}Object.defineProperty(_e,"__esModule",{value:!0});_e.checkTaprootInputForSigs=_e.tapTreeFromList=_e.tapTreeToList=_e.tweakInternalPubKey=_e.checkTaprootOutputFields=_e.checkTaprootInputFields=_e.isTaprootOutput=_e.isTaprootInput=hi=_e.serializeTaprootSignature=_e.tapScriptFinalizer=_e.toXOnly=void 0;const pf=qe,L6=fs,No=me,Rr=df,M6=lf(),D6=me,j6=e=>e.length===32?e:e.slice(1,33);_e.toXOnly=j6;function z6(e,t,r){const n=ax(t,e,r);try{const s=sx(t,n).concat(n.script).concat(n.controlBlock);return{finalScriptWitness:(0,No.witnessStackToScriptWitness)(s)}}catch(i){throw new Error(`Can not finalize taproot input #${e}: ${i}`)}}_e.tapScriptFinalizer=z6;function q6(e,t){const r=t?Buffer.from([t]):Buffer.from([]);return Buffer.concat([e,r])}var hi=_e.serializeTaprootSignature=q6;function js(e){return e&&!!(e.tapInternalKey||e.tapMerkleRoot||e.tapLeafScript&&e.tapLeafScript.length||e.tapBip32Derivation&&e.tapBip32Derivation.length||e.witnessUtxo&&(0,No.isP2TR)(e.witnessUtxo.script))}_e.isTaprootInput=js;function zs(e,t){return e&&!!(e.tapInternalKey||e.tapTree||e.tapBip32Derivation&&e.tapBip32Derivation.length||t&&(0,No.isP2TR)(t))}_e.isTaprootOutput=zs;function G6(e,t,r){rx(e,t,r),ix(e,t,r)}_e.checkTaprootInputFields=G6;function V6(e,t,r){nx(e,t,r),W6(e,t)}_e.checkTaprootOutputFields=V6;function W6(e,t){if(!t.tapTree&&!t.tapInternalKey)return;const r=t.tapInternalKey||e.tapInternalKey,n=t.tapTree||e.tapTree;if(r){const{script:i}=e,s=K6(r,n);if(i&&!i.equals(s))throw new Error("Error adding output. Script or address missmatch.")}}function K6(e,t){const r=t&&uy(t.leaves),{output:n}=(0,M6.p2tr)({internalPubkey:e,scriptTree:r});return n}function Y6(e,t){const r=t.tapInternalKey,n=r&&(0,Rr.tweakKey)(r,t.tapMerkleRoot);if(!n)throw new Error(`Cannot tweak tap internal key for input #${e}. Public key: ${r&&r.toString("hex")}`);return n.x}_e.tweakInternalPubKey=Y6;function Z6(e){if(!(0,pf.isTaptree)(e))throw new Error("Cannot convert taptree to tapleaf list. Expecting a tapree structure.");return su(e)}_e.tapTreeToList=Z6;function uy(e=[]){return e.length===1&&e[0].depth===0?{output:e[0].script,version:e[0].leafVersion}:tx(e)}_e.tapTreeFromList=uy;function X6(e,t){return Q6(e).some(n=>(0,D6.signatureBlocksAction)(n,J6,t))}_e.checkTaprootInputForSigs=X6;function J6(e){return{signature:e.slice(0,64),hashType:e.slice(64)[0]||L6.Transaction.SIGHASH_DEFAULT}}function Q6(e){const t=[];if(e.tapKeySig&&t.push(e.tapKeySig),e.tapScriptSig&&t.push(...e.tapScriptSig.map(r=>r.signature)),!t.length){const r=ex(e.finalScriptWitness);r&&t.push(r)}return t}function ex(e){if(!e)return;const t=e.slice(2);if(t.length===64||t.length===65)return t}function su(e,t=[],r=0){if(r>Rr.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return e?(0,pf.isTapleaf)(e)?(t.push({depth:r,leafVersion:e.version||Rr.LEAF_VERSION_TAPSCRIPT,script:e.output}),t):(e[0]&&su(e[0],t,r+1),e[1]&&su(e[1],t,r+1),t):[]}function tx(e){let t;for(const r of e)if(t=ou(r,t),!t)throw new Error("No room left to insert tapleaf in tree");return t}function ou(e,t,r=0){if(r>Rr.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");if(e.depth===r)return t?void 0:{output:e.script,version:e.leafVersion};if((0,pf.isTapleaf)(t))return;const n=ou(e,t&&t[0],r+1);if(n)return[n,t&&t[1]];const i=ou(e,t&&t[1],r+1);if(i)return[t&&t[0],i]}function rx(e,t,r){const n=js(e)&&On(t),i=On(e)&&js(t),s=e===t&&js(t)&&On(t);if(n||i||s)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function nx(e,t,r){const n=zs(e)&&On(t),i=On(e)&&zs(t),s=e===t&&zs(t)&&On(t);if(n||i||s)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function ix(e,t,r){if(t.tapMerkleRoot){const n=(t.tapLeafScript||[]).every(s=>ha(s,t.tapMerkleRoot)),i=(e.tapLeafScript||[]).every(s=>ha(s,t.tapMerkleRoot));if(!n||!i)throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}else if(e.tapMerkleRoot&&!(t.tapLeafScript||[]).every(i=>ha(i,e.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}function ha(e,t){if(!t)return!0;const r=(0,Rr.tapleafHash)({output:e.script,version:e.leafVersion});return(0,Rr.rootHashFromPath)(e.controlBlock,r).equals(t)}function sx(e,t){const r=(0,Rr.tapleafHash)({output:t.script,version:t.leafVersion});return(e.tapScriptSig||[]).filter(n=>n.leafHash.equals(r)).map(n=>ox(t.script,n)).sort((n,i)=>i.positionInScript-n.positionInScript).map(n=>n.signature)}function ox(e,t){return Object.assign({positionInScript:(0,No.pubkeyPositionInScript)(t.pubkey,e)},t)}function ax(e,t,r){if(!e.tapScriptSig||!e.tapScriptSig.length)throw new Error(`Can not finalize taproot input #${t}. No tapleaf script signature provided.`);const n=(e.tapLeafScript||[]).sort((i,s)=>i.controlBlock.length-s.controlBlock.length).find(i=>cx(i,e.tapScriptSig,r));if(!n)throw new Error(`Can not finalize taproot input #${t}. Signature for tapleaf script not found.`);return n}function cx(e,t,r){const n=(0,Rr.tapleafHash)({output:e.script,version:e.leafVersion});return(!r||r.equals(n))&&t.find(s=>s.leafHash.equals(n))!==void 0}function On(e){return e&&!!(e.redeemScript||e.witnessScript||e.bip32Derivation&&e.bip32Derivation.length)}const Ze={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:e=>"counterparty signature not found for utxo "+e,invalidCounterpartySigForUTXO:e=>"invalid counterparty signature for utxo "+e,htlcNotExpired:e=>`HTLC not expired, need more ${e} blocks`,controlBlockGenerationFailed:"failed to generate control block",invalidLeaf:"invalid leaf"},Os=192;pe.initEccLib(bt);class Ei{constructor(t,r,n,i,s,o,a,c){this.secretHash=n,this.redeemerPubkey=i,this.initiatorPubkey=s,this.expiry=o,this.signer=t,this.network=a,this.internalPubkey=aE(),this.initiateAmount=r,this.utxoHashes=c}static async from(t,r,n,i,s,o,a){n=n.startsWith("0x")?n.slice(2):n,yn(n.length===64,Ze.secretHashLenMismatch),yn(i.length===64||i.length===66,`initiator ${Ze.pubkeyLenMismatch}`),yn(s.length===64||s.length===66,`redeemer ${Ze.pubkeyLenMismatch}`),yn(o>0,Ze.zeroOrNegativeExpiry);const c=await t.getNetwork();return new Ei(t,r,n,Qc(s).toString("hex"),Qc(i).toString("hex"),o,c,a)}address(){const{address:t}=pe.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves()});if(!t)throw new Error(Ze.htlcAddressGenerationFailed);return t}id(){return this.address()}async _buildRawTx(t,r){const n=new pe.Transaction;n.version=2;const i=this.address(),s=await this.signer.getProvider();let o=[];if(this.utxoHashes&&this.utxoHashes.length>0)for(const f of this.utxoHashes){const u=await s.getTransaction(f);for(let d=0;d<u.vout.length;d++){const y=u.vout[d];y.scriptpubkey_address===i&&o.push({txid:u.txid,vout:d,value:y.value,status:{confirmed:!1}})}}else o=await s.getUTXOs(i);const a=o.reduce((f,u)=>f+u.value,0);if(a===0)throw new Error(`${i} ${Ze.notFunded}`);for(let f=0;f<o.length;f++)n.addInput(Buffer.from(o[f].txid,"hex").reverse(),o[f].vout);if(r!=null&&r.vSize){const f=await s.getFeeRates(),u=Math.ceil(f.hourFee*r.vSize),d=a-u;return n.addOutput(pe.address.toOutputScript(t,this.network),d),{tx:n,usedUtxos:o}}const c=(r==null?void 0:r.fee)??await s.suggestFee(i,a,In.MEDIUM);return n.addOutput(pe.address.toOutputScript(t,this.network),a-c),{tx:n,usedUtxos:o,fee:c,balance:a}}getOutputScript(){return pe.address.toOutputScript(this.address(),this.network)}async init(t){return t??(t=await(await this.signer.getProvider()).suggestFee(await this.signer.getAddress(),this.initiateAmount,In.MEDIUM)),await this.signer.send(this.address(),this.initiateAmount,t)}async generateRedeemSACP(t,r,n){const{tx:i,usedUtxos:s}=await this._buildRawTx(r,{fee:n}),o=this.getOutputScript(),a=pe.Transaction.SIGHASH_SINGLE|pe.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(1),f=s.map(d=>d.value),u=ai(o,s.length);for(let d=0;d<i.ins.length;d++){const y=i.hashForWitnessV1(d,u,f,a,c),p=await this.signer.signSchnorr(y);i.setWitness(d,[hi(p,a),Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}return i.toHex()}async generateInstantRefundSACP(t){const r=this.getOutputScript(),{tx:n,usedUtxos:i,fee:s}=await this._buildRawTx(t,{fee:0});n.outs=[];const o=Math.max(...i.map(d=>d.value));i.forEach(({value:d})=>{n.addOutput(r,d-(d===o?s??0:0))});const a=pe.Transaction.SIGHASH_SINGLE|pe.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(2),f=i.map(d=>d.value),u=ai(r,i.length);for(let d=0;d<n.ins.length;d++){const y=n.hashForWitnessV1(d,u,f,a,c),p=await this.signer.signSchnorr(y);n.setWitness(d,[hi(p,a),hi(p,a),this.instantRefundLeaf(),this.generateControlBlockFor(2)])}return n.toHex()}async generateInstantRefundSACPWithHash(t){const r=[],n=pe.Transaction.SIGHASH_SINGLE|pe.Transaction.SIGHASH_ANYONECANPAY;for(let i=0;i<t.length;i++){const s=Buffer.from(t[i],"hex"),o=await this.signer.signSchnorr(s);r.push(hi(o,n).toString("hex"))}return r}async instantRefund(t,r){yn(t.length>0,Ze.noCounterpartySigs);const{tx:n,usedUtxos:i}=await this._buildRawTx(await this.signer.getAddress(),{fee:r});for(const d of i)if(!t.find(y=>y.utxo===d.txid))throw new Error(Ze.counterPartySigNotFound(d.txid));const s=this.getOutputScript(),o=pe.Transaction.SIGHASH_DEFAULT,a=this.leafHash(2),c=i.map(d=>d.value),f=ai(s,i.length);for(let d=0;d<n.ins.length;d++){const y=n.hashForWitnessV1(d,f,c,o,a);if(!bt.verifySchnorr(y,Buffer.from(this.redeemerPubkey,"hex"),Buffer.from(t[d].sig,"hex")))throw new Error(Ze.invalidCounterpartySigForUTXO(t[d].utxo));const p=await this.signer.signSchnorr(y),g=Buffer.from(n.ins[d].hash).reverse().toString("hex"),b=t.find(E=>E.utxo===g);if(!b)throw new Error(Ze.counterPartySigNotFound(g));n.setWitness(d,[Buffer.from(b.sig,"hex"),p,this.instantRefundLeaf(),this.generateControlBlockFor(2)])}return await(await this.signer.getProvider()).broadcast(n.toHex())}async redeem(t,r){const n=await this.getRedeemHex(t,r);return await(await this.signer.getProvider()).broadcast(n)}async getRedeemHex(t,r){yn(pe.crypto.sha256(Buffer.from(t,"hex")).toString("hex")===this.secretHash,Ze.secretMismatch);const n=r??await this.signer.getAddress(),{tx:i,usedUtxos:s}=await this._buildRawTx(n,{fee:0}),o=this.leafHash(1),a=s.map(d=>d.value),c=ai(this.getOutputScript(),s.length),f=pe.Transaction.SIGHASH_DEFAULT;for(let d=0;d<i.ins.length;d++){const y=i.hashForWitnessV1(d,c,a,f,o),p=await this.signer.signSchnorr(y);i.setWitness(d,[p,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}const{tx:u}=await this._buildRawTx(n,{vSize:i.virtualSize()});for(let d=0;d<u.ins.length;d++){const y=u.hashForWitnessV1(d,c,a,f,o),p=await this.signer.signSchnorr(y);u.setWitness(d,[p,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}return u.toHex()}async refund(t,r){const{tx:n,usedUtxos:i}=await this._buildRawTx(t??await this.signer.getAddress(),{fee:r}),[s,o]=await this.canRefund(i);if(!s)throw new Error(Ze.htlcNotExpired(o));const a=this.leafHash(0),c=i.map(y=>y.value),f=ai(this.getOutputScript(),i.length),u=pe.Transaction.SIGHASH_DEFAULT;for(let y=0;y<n.ins.length;y++){n.ins[y].sequence=this.expiry;const p=n.hashForWitnessV1(y,f,c,u,a),g=await this.signer.signSchnorr(p);n.setWitness(y,[g,this.refundLeaf(),this.generateControlBlockFor(0)])}return await(await this.signer.getProvider()).broadcast(n.toHex())}async canRefund(t){const n=await(await this.signer.getProvider()).getLatestTip();for(const i of t){let s=0;if(i.status.confirmed&&i.status.block_height+this.expiry>n?s=i.status.block_height+this.expiry-n+1:i.status.confirmed||(s=this.expiry+1),s>0)return[!1,s]}return[!0,0]}generateControlBlockFor(t){let r;switch(t){case 1:r=this.redeemLeaf();break;case 0:r=this.refundLeaf();break;case 2:r=this.instantRefundLeaf();break;default:throw new Error(Ze.invalidLeaf)}const n=pe.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves(),redeem:{output:r,redeemVersion:Os}});if(!n.witness)throw new Error(Ze.controlBlockGenerationFailed);return n.witness[n.witness.length-1]}leafHash(t){let r=this.redeemLeaf();return t===0&&(r=this.refundLeaf()),t===2&&(r=this.instantRefundLeaf()),pe.crypto.taggedHash("TapLeaf",Wv(r))}refundLeaf(){return pe.script.fromASM(`
53
+ `,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var ft={};Object.defineProperty(ft,"__esModule",{value:!0});ft.value=ft.prop=void 0;function QE(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){const n=r.call(this);return this[t]=n,n},set(n){Object.defineProperty(this,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}})}ft.prop=QE;function e6(e){let t;return()=>(t!==void 0||(t=e()),t)}ft.value=e6;Object.defineProperty(To,"__esModule",{value:!0});To.p2data=void 0;const t6=ze,Ms=pt(),Lt=qe,Id=ft,kd=Ms.OPS;function r6(e,t){if(!e.data&&!e.output)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Lt.typeforce)({network:Lt.typeforce.maybe(Lt.typeforce.Object),output:Lt.typeforce.maybe(Lt.typeforce.Buffer),data:Lt.typeforce.maybe(Lt.typeforce.arrayOf(Lt.typeforce.Buffer))},e);const n={name:"embed",network:e.network||t6.bitcoin};if(Id.prop(n,"output",()=>{if(e.data)return Ms.compile([kd.OP_RETURN].concat(e.data))}),Id.prop(n,"data",()=>{if(e.output)return Ms.decompile(e.output).slice(1)}),t.validate&&e.output){const i=Ms.decompile(e.output);if(i[0]!==kd.OP_RETURN)throw new TypeError("Output is invalid");if(!i.slice(1).every(Lt.typeforce.Buffer))throw new TypeError("Output is invalid");if(e.data&&!(0,Lt.stacksEqual)(e.data,n.data))throw new TypeError("Data mismatch")}return Object.assign(n,e)}To.p2data=r6;var Io={};Object.defineProperty(Io,"__esModule",{value:!0});Io.p2ms=void 0;const n6=ze,wn=pt(),Ie=qe,vr=ft,vn=wn.OPS,Ps=vn.OP_RESERVED;function i6(e,t){if(!e.input&&!e.output&&!(e.pubkeys&&e.m!==void 0)&&!e.signatures)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{});function r(c){return wn.isCanonicalScriptSignature(c)||(t.allowIncomplete&&c===vn.OP_0)!==void 0}(0,Ie.typeforce)({network:Ie.typeforce.maybe(Ie.typeforce.Object),m:Ie.typeforce.maybe(Ie.typeforce.Number),n:Ie.typeforce.maybe(Ie.typeforce.Number),output:Ie.typeforce.maybe(Ie.typeforce.Buffer),pubkeys:Ie.typeforce.maybe(Ie.typeforce.arrayOf(Ie.isPoint)),signatures:Ie.typeforce.maybe(Ie.typeforce.arrayOf(r)),input:Ie.typeforce.maybe(Ie.typeforce.Buffer)},e);const i={network:e.network||n6.bitcoin};let s=[],o=!1;function a(c){o||(o=!0,s=wn.decompile(c),i.m=s[0]-Ps,i.n=s[s.length-2]-Ps,i.pubkeys=s.slice(1,-2))}if(vr.prop(i,"output",()=>{if(e.m&&i.n&&e.pubkeys)return wn.compile([].concat(Ps+e.m,e.pubkeys,Ps+i.n,vn.OP_CHECKMULTISIG))}),vr.prop(i,"m",()=>{if(i.output)return a(i.output),i.m}),vr.prop(i,"n",()=>{if(i.pubkeys)return i.pubkeys.length}),vr.prop(i,"pubkeys",()=>{if(e.output)return a(e.output),i.pubkeys}),vr.prop(i,"signatures",()=>{if(e.input)return wn.decompile(e.input).slice(1)}),vr.prop(i,"input",()=>{if(e.signatures)return wn.compile([vn.OP_0].concat(e.signatures))}),vr.prop(i,"witness",()=>{if(i.input)return[]}),vr.prop(i,"name",()=>{if(!(!i.m||!i.n))return`p2ms(${i.m} of ${i.n})`}),t.validate){if(e.output){if(a(e.output),!Ie.typeforce.Number(s[0]))throw new TypeError("Output is invalid");if(!Ie.typeforce.Number(s[s.length-2]))throw new TypeError("Output is invalid");if(s[s.length-1]!==vn.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(i.m<=0||i.n>16||i.m>i.n||i.n!==s.length-3)throw new TypeError("Output is invalid");if(!i.pubkeys.every(c=>(0,Ie.isPoint)(c)))throw new TypeError("Output is invalid");if(e.m!==void 0&&e.m!==i.m)throw new TypeError("m mismatch");if(e.n!==void 0&&e.n!==i.n)throw new TypeError("n mismatch");if(e.pubkeys&&!(0,Ie.stacksEqual)(e.pubkeys,i.pubkeys))throw new TypeError("Pubkeys mismatch")}if(e.pubkeys){if(e.n!==void 0&&e.n!==e.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(i.n=e.pubkeys.length,i.n<i.m)throw new TypeError("Pubkey count cannot be less than m")}if(e.signatures){if(e.signatures.length<i.m)throw new TypeError("Not enough signatures provided");if(e.signatures.length>i.m)throw new TypeError("Too many signatures provided")}if(e.input){if(e.input[0]!==vn.OP_0)throw new TypeError("Input is invalid");if(i.signatures.length===0||!i.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(e.signatures&&!(0,Ie.stacksEqual)(e.signatures,i.signatures))throw new TypeError("Signature mismatch");if(e.m!==void 0&&e.m!==e.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(i,e)}Io.p2ms=i6;var ko={};Object.defineProperty(ko,"__esModule",{value:!0});ko.p2pk=void 0;const s6=ze,En=pt(),_t=qe,gn=ft,Bd=En.OPS;function o6(e,t){if(!e.input&&!e.output&&!e.pubkey&&!e.input&&!e.signature)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,_t.typeforce)({network:_t.typeforce.maybe(_t.typeforce.Object),output:_t.typeforce.maybe(_t.typeforce.Buffer),pubkey:_t.typeforce.maybe(_t.isPoint),signature:_t.typeforce.maybe(En.isCanonicalScriptSignature),input:_t.typeforce.maybe(_t.typeforce.Buffer)},e);const r=gn.value(()=>En.decompile(e.input)),i={name:"p2pk",network:e.network||s6.bitcoin};if(gn.prop(i,"output",()=>{if(e.pubkey)return En.compile([e.pubkey,Bd.OP_CHECKSIG])}),gn.prop(i,"pubkey",()=>{if(e.output)return e.output.slice(1,-1)}),gn.prop(i,"signature",()=>{if(e.input)return r()[0]}),gn.prop(i,"input",()=>{if(e.signature)return En.compile([e.signature])}),gn.prop(i,"witness",()=>{if(i.input)return[]}),t.validate){if(e.output){if(e.output[e.output.length-1]!==Bd.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!(0,_t.isPoint)(i.pubkey))throw new TypeError("Output pubkey is invalid");if(e.pubkey&&!e.pubkey.equals(i.pubkey))throw new TypeError("Pubkey mismatch")}if(e.signature&&e.input&&!e.input.equals(i.input))throw new TypeError("Signature mismatch");if(e.input){if(r().length!==1)throw new TypeError("Input is invalid");if(!En.isCanonicalScriptSignature(i.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(i,e)}ko.p2pk=o6;var Bo={};function a6(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var n=0;n<e.length;n++){var i=e.charAt(n),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=n}var o=e.length,a=e.charAt(0),c=Math.log(o)/Math.log(256),f=Math.log(256)/Math.log(o);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,b=0,E=0,A=p.length;E!==A&&p[E]===0;)E++,g++;for(var P=(A-E)*f+1>>>0,w=new Uint8Array(P);E!==A;){for(var _=p[E],T=0,I=P-1;(_!==0||T<b)&&I!==-1;I--,T++)_+=256*w[I]>>>0,w[I]=_%o>>>0,_=_/o>>>0;if(_!==0)throw new Error("Non-zero carry");b=T,E++}for(var R=P-b;R!==P&&w[R]===0;)R++;for(var L=a.repeat(g);R<P;++R)L+=e.charAt(w[R]);return L}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;for(var g=0,b=0,E=0;p[g]===a;)b++,g++;for(var A=(p.length-g)*c+1>>>0,P=new Uint8Array(A);p[g];){var w=p.charCodeAt(g);if(w>255)return;var _=t[w];if(_===255)return;for(var T=0,I=A-1;(_!==0||T<E)&&I!==-1;I--,T++)_+=o*P[I]>>>0,P[I]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");E=T,g++}for(var R=A-E;R!==A&&P[R]===0;)R++;for(var L=new Uint8Array(b+(A-R)),S=b;R!==A;)L[S++]=P[R++];return L}function y(p){var g=d(p);if(g)return g;throw new Error("Non-base"+o+" character")}return{encode:u,decodeUnsafe:d,decode:y}}var c6=a6;const u6=c6,f6="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";var d6=u6(f6),fa=d6,l6=function(e){function t(s){var o=Uint8Array.from(s),a=e(o),c=o.length+4,f=new Uint8Array(c);return f.set(o,0),f.set(a.subarray(0,4),o.length),fa.encode(f,c)}function r(s){var o=s.slice(0,-4),a=s.slice(-4),c=e(o);if(!(a[0]^c[0]|a[1]^c[1]|a[2]^c[2]|a[3]^c[3]))return o}function n(s){var o=fa.decodeUnsafe(s);if(o)return r(o)}function i(s){var o=fa.decode(s),a=r(o);if(!a)throw new Error("Invalid checksum");return a}return{encode:t,decode:i,decodeUnsafe:n}},{sha256:Od}=ty,p6=l6;function h6(e){return Od(Od(e))}var uf=p6(h6);Object.defineProperty(Bo,"__esModule",{value:!0});Bo.p2pkh=void 0;const da=Nr,y6=ze,xn=pt(),Ke=qe,Qt=ft,Cd=uf,Er=xn.OPS;function m6(e,t){if(!e.address&&!e.hash&&!e.output&&!e.pubkey&&!e.input)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Ke.typeforce)({network:Ke.typeforce.maybe(Ke.typeforce.Object),address:Ke.typeforce.maybe(Ke.typeforce.String),hash:Ke.typeforce.maybe(Ke.typeforce.BufferN(20)),output:Ke.typeforce.maybe(Ke.typeforce.BufferN(25)),pubkey:Ke.typeforce.maybe(Ke.isPoint),signature:Ke.typeforce.maybe(xn.isCanonicalScriptSignature),input:Ke.typeforce.maybe(Ke.typeforce.Buffer)},e);const r=Qt.value(()=>{const o=Buffer.from(Cd.decode(e.address)),a=o.readUInt8(0),c=o.slice(1);return{version:a,hash:c}}),n=Qt.value(()=>xn.decompile(e.input)),i=e.network||y6.bitcoin,s={name:"p2pkh",network:i};if(Qt.prop(s,"address",()=>{if(!s.hash)return;const o=Buffer.allocUnsafe(21);return o.writeUInt8(i.pubKeyHash,0),s.hash.copy(o,1),Cd.encode(o)}),Qt.prop(s,"hash",()=>{if(e.output)return e.output.slice(3,23);if(e.address)return r().hash;if(e.pubkey||s.pubkey)return da.hash160(e.pubkey||s.pubkey)}),Qt.prop(s,"output",()=>{if(s.hash)return xn.compile([Er.OP_DUP,Er.OP_HASH160,s.hash,Er.OP_EQUALVERIFY,Er.OP_CHECKSIG])}),Qt.prop(s,"pubkey",()=>{if(e.input)return n()[1]}),Qt.prop(s,"signature",()=>{if(e.input)return n()[0]}),Qt.prop(s,"input",()=>{if(e.pubkey&&e.signature)return xn.compile([e.signature,e.pubkey])}),Qt.prop(s,"witness",()=>{if(s.input)return[]}),t.validate){let o=Buffer.from([]);if(e.address){if(r().version!==i.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(r().hash.length!==20)throw new TypeError("Invalid address");o=r().hash}if(e.hash){if(o.length>0&&!o.equals(e.hash))throw new TypeError("Hash mismatch");o=e.hash}if(e.output){if(e.output.length!==25||e.output[0]!==Er.OP_DUP||e.output[1]!==Er.OP_HASH160||e.output[2]!==20||e.output[23]!==Er.OP_EQUALVERIFY||e.output[24]!==Er.OP_CHECKSIG)throw new TypeError("Output is invalid");const a=e.output.slice(3,23);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(e.pubkey){const a=da.hash160(e.pubkey);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(e.input){const a=n();if(a.length!==2)throw new TypeError("Input is invalid");if(!xn.isCanonicalScriptSignature(a[0]))throw new TypeError("Input has invalid signature");if(!(0,Ke.isPoint)(a[1]))throw new TypeError("Input has invalid pubkey");if(e.signature&&!e.signature.equals(a[0]))throw new TypeError("Signature mismatch");if(e.pubkey&&!e.pubkey.equals(a[1]))throw new TypeError("Pubkey mismatch");const c=da.hash160(a[1]);if(o.length>0&&!o.equals(c))throw new TypeError("Hash mismatch")}}return Object.assign(s,e)}Bo.p2pkh=m6;var Oo={};Object.defineProperty(Oo,"__esModule",{value:!0});Oo.p2sh=void 0;const Rd=Nr,g6=ze,jt=pt(),be=qe,Mt=ft,Nd=uf,si=jt.OPS;function b6(e,t){if(!e.address&&!e.hash&&!e.output&&!e.redeem&&!e.input)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,be.typeforce)({network:be.typeforce.maybe(be.typeforce.Object),address:be.typeforce.maybe(be.typeforce.String),hash:be.typeforce.maybe(be.typeforce.BufferN(20)),output:be.typeforce.maybe(be.typeforce.BufferN(23)),redeem:be.typeforce.maybe({network:be.typeforce.maybe(be.typeforce.Object),output:be.typeforce.maybe(be.typeforce.Buffer),input:be.typeforce.maybe(be.typeforce.Buffer),witness:be.typeforce.maybe(be.typeforce.arrayOf(be.typeforce.Buffer))}),input:be.typeforce.maybe(be.typeforce.Buffer),witness:be.typeforce.maybe(be.typeforce.arrayOf(be.typeforce.Buffer))},e);let r=e.network;r||(r=e.redeem&&e.redeem.network||g6.bitcoin);const n={network:r},i=Mt.value(()=>{const a=Buffer.from(Nd.decode(e.address)),c=a.readUInt8(0),f=a.slice(1);return{version:c,hash:f}}),s=Mt.value(()=>jt.decompile(e.input)),o=Mt.value(()=>{const a=s(),c=a[a.length-1];return{network:r,output:c===si.OP_FALSE?Buffer.from([]):c,input:jt.compile(a.slice(0,-1)),witness:e.witness||[]}});if(Mt.prop(n,"address",()=>{if(!n.hash)return;const a=Buffer.allocUnsafe(21);return a.writeUInt8(n.network.scriptHash,0),n.hash.copy(a,1),Nd.encode(a)}),Mt.prop(n,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return i().hash;if(n.redeem&&n.redeem.output)return Rd.hash160(n.redeem.output)}),Mt.prop(n,"output",()=>{if(n.hash)return jt.compile([si.OP_HASH160,n.hash,si.OP_EQUAL])}),Mt.prop(n,"redeem",()=>{if(e.input)return o()}),Mt.prop(n,"input",()=>{if(!(!e.redeem||!e.redeem.input||!e.redeem.output))return jt.compile([].concat(jt.decompile(e.redeem.input),e.redeem.output))}),Mt.prop(n,"witness",()=>{if(n.redeem&&n.redeem.witness)return n.redeem.witness;if(n.input)return[]}),Mt.prop(n,"name",()=>{const a=["p2sh"];return n.redeem!==void 0&&n.redeem.name!==void 0&&a.push(n.redeem.name),a.join("-")}),t.validate){let a=Buffer.from([]);if(e.address){if(i().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(i().hash.length!==20)throw new TypeError("Invalid address");a=i().hash}if(e.hash){if(a.length>0&&!a.equals(e.hash))throw new TypeError("Hash mismatch");a=e.hash}if(e.output){if(e.output.length!==23||e.output[0]!==si.OP_HASH160||e.output[1]!==20||e.output[22]!==si.OP_EQUAL)throw new TypeError("Output is invalid");const f=e.output.slice(2,22);if(a.length>0&&!a.equals(f))throw new TypeError("Hash mismatch");a=f}const c=f=>{if(f.output){const u=jt.decompile(f.output);if(!u||u.length<1)throw new TypeError("Redeem.output too short");if(f.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(jt.countNonPushOnlyOPs(u)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const d=Rd.hash160(f.output);if(a.length>0&&!a.equals(d))throw new TypeError("Hash mismatch");a=d}if(f.input){const u=f.input.length>0,d=f.witness&&f.witness.length>0;if(!u&&!d)throw new TypeError("Empty input");if(u&&d)throw new TypeError("Input and witness provided");if(u){const y=jt.decompile(f.input);if(!jt.isPushOnly(y))throw new TypeError("Non push-only scriptSig")}}};if(e.input){const f=s();if(!f||f.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(o().output))throw new TypeError("Input is invalid");c(o())}if(e.redeem){if(e.redeem.network&&e.redeem.network!==r)throw new TypeError("Network mismatch");if(e.input){const f=o();if(e.redeem.output&&!e.redeem.output.equals(f.output))throw new TypeError("Redeem.output mismatch");if(e.redeem.input&&!e.redeem.input.equals(f.input))throw new TypeError("Redeem.input mismatch")}c(e.redeem)}if(e.witness&&e.redeem&&e.redeem.witness&&!(0,be.stacksEqual)(e.redeem.witness,e.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,e)}Oo.p2sh=b6;var Co={},dr={};Object.defineProperty(dr,"__esModule",{value:!0});dr.bech32m=dr.bech32=void 0;const Zs="qpzry9x8gf2tvdw0s3jn54khce6mua7l",sy={};for(let e=0;e<Zs.length;e++){const t=Zs.charAt(e);sy[t]=e}function Bn(e){const t=e>>25;return(e&33554431)<<5^-(t>>0&1)&996825010^-(t>>1&1)&642813549^-(t>>2&1)&513874426^-(t>>3&1)&1027748829^-(t>>4&1)&705979059}function Fd(e){let t=1;for(let r=0;r<e.length;++r){const n=e.charCodeAt(r);if(n<33||n>126)return"Invalid prefix ("+e+")";t=Bn(t)^n>>5}t=Bn(t);for(let r=0;r<e.length;++r){const n=e.charCodeAt(r);t=Bn(t)^n&31}return t}function ff(e,t,r,n){let i=0,s=0;const o=(1<<r)-1,a=[];for(let c=0;c<e.length;++c)for(i=i<<t|e[c],s+=t;s>=r;)s-=r,a.push(i>>s&o);if(n)s>0&&a.push(i<<r-s&o);else{if(s>=t)return"Excess padding";if(i<<r-s&o)return"Non-zero padding"}return a}function w6(e){return ff(e,8,5,!0)}function v6(e){const t=ff(e,5,8,!1);if(Array.isArray(t))return t}function E6(e){const t=ff(e,5,8,!1);if(Array.isArray(t))return t;throw new Error(t)}function oy(e){let t;e==="bech32"?t=1:t=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 f=Fd(o);if(typeof f=="string")throw new Error(f);let u=o+"1";for(let d=0;d<a.length;++d){const y=a[d];if(y>>5)throw new Error("Non 5-bit word");f=Bn(f)^y,u+=Zs.charAt(y)}for(let d=0;d<6;++d)f=Bn(f);f^=t;for(let d=0;d<6;++d){const y=f>>(5-d)*5&31;u+=Zs.charAt(y)}return u}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(),f=o.toUpperCase();if(o!==c&&o!==f)return"Mixed-case string "+o;o=c;const u=o.lastIndexOf("1");if(u===-1)return"No separator character for "+o;if(u===0)return"Missing prefix for "+o;const d=o.slice(0,u),y=o.slice(u+1);if(y.length<6)return"Data too short";let p=Fd(d);if(typeof p=="string")return p;const g=[];for(let b=0;b<y.length;++b){const E=y.charAt(b),A=sy[E];if(A===void 0)return"Unknown character "+E;p=Bn(p)^A,!(b+6>=y.length)&&g.push(A)}return p!==t?"Invalid checksum for "+o:{prefix:d,words:g}}function i(o,a){const c=n(o,a);if(typeof c=="object")return c}function s(o,a){const c=n(o,a);if(typeof c=="object")return c;throw new Error(c)}return{decodeUnsafe:i,decode:s,encode:r,toWords:w6,fromWordsUnsafe:v6,fromWords:E6}}dr.bech32=oy("bech32");dr.bech32m=oy("bech32m");Object.defineProperty(Co,"__esModule",{value:!0});Co.p2wpkh=void 0;const la=Nr,x6=ze,Ds=pt(),Ne=qe,xr=ft,Ts=dr,$d=Ds.OPS,A6=Buffer.alloc(0);function _6(e,t){if(!e.address&&!e.hash&&!e.output&&!e.pubkey&&!e.witness)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Ne.typeforce)({address:Ne.typeforce.maybe(Ne.typeforce.String),hash:Ne.typeforce.maybe(Ne.typeforce.BufferN(20)),input:Ne.typeforce.maybe(Ne.typeforce.BufferN(0)),network:Ne.typeforce.maybe(Ne.typeforce.Object),output:Ne.typeforce.maybe(Ne.typeforce.BufferN(22)),pubkey:Ne.typeforce.maybe(Ne.isPoint),signature:Ne.typeforce.maybe(Ds.isCanonicalScriptSignature),witness:Ne.typeforce.maybe(Ne.typeforce.arrayOf(Ne.typeforce.Buffer))},e);const r=xr.value(()=>{const s=Ts.bech32.decode(e.address),o=s.words.shift(),a=Ts.bech32.fromWords(s.words);return{version:o,prefix:s.prefix,data:Buffer.from(a)}}),n=e.network||x6.bitcoin,i={name:"p2wpkh",network:n};if(xr.prop(i,"address",()=>{if(!i.hash)return;const s=Ts.bech32.toWords(i.hash);return s.unshift(0),Ts.bech32.encode(n.bech32,s)}),xr.prop(i,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return r().data;if(e.pubkey||i.pubkey)return la.hash160(e.pubkey||i.pubkey)}),xr.prop(i,"output",()=>{if(i.hash)return Ds.compile([$d.OP_0,i.hash])}),xr.prop(i,"pubkey",()=>{if(e.pubkey)return e.pubkey;if(e.witness)return e.witness[1]}),xr.prop(i,"signature",()=>{if(e.witness)return e.witness[0]}),xr.prop(i,"input",()=>{if(i.witness)return A6}),xr.prop(i,"witness",()=>{if(e.pubkey&&e.signature)return[e.signature,e.pubkey]}),t.validate){let s=Buffer.from([]);if(e.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");s=r().data}if(e.hash){if(s.length>0&&!s.equals(e.hash))throw new TypeError("Hash mismatch");s=e.hash}if(e.output){if(e.output.length!==22||e.output[0]!==$d.OP_0||e.output[1]!==20)throw new TypeError("Output is invalid");if(s.length>0&&!s.equals(e.output.slice(2)))throw new TypeError("Hash mismatch");s=e.output.slice(2)}if(e.pubkey){const o=la.hash160(e.pubkey);if(s.length>0&&!s.equals(o))throw new TypeError("Hash mismatch");if(s=o,!(0,Ne.isPoint)(e.pubkey)||e.pubkey.length!==33)throw new TypeError("Invalid pubkey for p2wpkh")}if(e.witness){if(e.witness.length!==2)throw new TypeError("Witness is invalid");if(!Ds.isCanonicalScriptSignature(e.witness[0]))throw new TypeError("Witness has invalid signature");if(!(0,Ne.isPoint)(e.witness[1])||e.witness[1].length!==33)throw new TypeError("Witness has invalid pubkey");if(e.signature&&!e.signature.equals(e.witness[0]))throw new TypeError("Signature mismatch");if(e.pubkey&&!e.pubkey.equals(e.witness[1]))throw new TypeError("Pubkey mismatch");const o=la.hash160(e.witness[1]);if(s.length>0&&!s.equals(o))throw new TypeError("Hash mismatch")}}return Object.assign(i,e)}Co.p2wpkh=_6;var Ro={};Object.defineProperty(Ro,"__esModule",{value:!0});Ro.p2wsh=void 0;const Ud=Nr,S6=ze,rr=pt(),ge=qe,er=ft,Is=dr,Hd=rr.OPS,pa=Buffer.alloc(0);function ks(e){return!!(Buffer.isBuffer(e)&&e.length===65&&e[0]===4&&(0,ge.isPoint)(e))}function P6(e,t){if(!e.address&&!e.hash&&!e.output&&!e.redeem&&!e.witness)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,ge.typeforce)({network:ge.typeforce.maybe(ge.typeforce.Object),address:ge.typeforce.maybe(ge.typeforce.String),hash:ge.typeforce.maybe(ge.typeforce.BufferN(32)),output:ge.typeforce.maybe(ge.typeforce.BufferN(34)),redeem:ge.typeforce.maybe({input:ge.typeforce.maybe(ge.typeforce.Buffer),network:ge.typeforce.maybe(ge.typeforce.Object),output:ge.typeforce.maybe(ge.typeforce.Buffer),witness:ge.typeforce.maybe(ge.typeforce.arrayOf(ge.typeforce.Buffer))}),input:ge.typeforce.maybe(ge.typeforce.BufferN(0)),witness:ge.typeforce.maybe(ge.typeforce.arrayOf(ge.typeforce.Buffer))},e);const r=er.value(()=>{const o=Is.bech32.decode(e.address),a=o.words.shift(),c=Is.bech32.fromWords(o.words);return{version:a,prefix:o.prefix,data:Buffer.from(c)}}),n=er.value(()=>rr.decompile(e.redeem.input));let i=e.network;i||(i=e.redeem&&e.redeem.network||S6.bitcoin);const s={network:i};if(er.prop(s,"address",()=>{if(!s.hash)return;const o=Is.bech32.toWords(s.hash);return o.unshift(0),Is.bech32.encode(i.bech32,o)}),er.prop(s,"hash",()=>{if(e.output)return e.output.slice(2);if(e.address)return r().data;if(s.redeem&&s.redeem.output)return Ud.sha256(s.redeem.output)}),er.prop(s,"output",()=>{if(s.hash)return rr.compile([Hd.OP_0,s.hash])}),er.prop(s,"redeem",()=>{if(e.witness)return{output:e.witness[e.witness.length-1],input:pa,witness:e.witness.slice(0,-1)}}),er.prop(s,"input",()=>{if(s.witness)return pa}),er.prop(s,"witness",()=>{if(e.redeem&&e.redeem.input&&e.redeem.input.length>0&&e.redeem.output&&e.redeem.output.length>0){const o=rr.toStack(n());return s.redeem=Object.assign({witness:o},e.redeem),s.redeem.input=pa,[].concat(o,e.redeem.output)}if(e.redeem&&e.redeem.output&&e.redeem.witness)return[].concat(e.redeem.witness,e.redeem.output)}),er.prop(s,"name",()=>{const o=["p2wsh"];return s.redeem!==void 0&&s.redeem.name!==void 0&&o.push(s.redeem.name),o.join("-")}),t.validate){let o=Buffer.from([]);if(e.address){if(r().prefix!==i.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(e.hash){if(o.length>0&&!o.equals(e.hash))throw new TypeError("Hash mismatch");o=e.hash}if(e.output){if(e.output.length!==34||e.output[0]!==Hd.OP_0||e.output[1]!==32)throw new TypeError("Output is invalid");const a=e.output.slice(2);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(e.redeem){if(e.redeem.network&&e.redeem.network!==i)throw new TypeError("Network mismatch");if(e.redeem.input&&e.redeem.input.length>0&&e.redeem.witness&&e.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(e.redeem.output){const a=rr.decompile(e.redeem.output);if(!a||a.length<1)throw new TypeError("Redeem.output is invalid");if(e.redeem.output.byteLength>3600)throw new TypeError("Redeem.output unspendable if larger than 3600 bytes");if(rr.countNonPushOnlyOPs(a)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const c=Ud.sha256(e.redeem.output);if(o.length>0&&!o.equals(c))throw new TypeError("Hash mismatch");o=c}if(e.redeem.input&&!rr.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(e.witness&&e.redeem.witness&&!(0,ge.stacksEqual)(e.witness,e.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(e.redeem.input&&n().some(ks)||e.redeem.output&&(rr.decompile(e.redeem.output)||[]).some(ks))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(e.witness&&e.witness.length>0){const a=e.witness[e.witness.length-1];if(e.redeem&&e.redeem.output&&!e.redeem.output.equals(a))throw new TypeError("Witness and redeem.output mismatch");if(e.witness.some(ks)||(rr.decompile(a)||[]).some(ks))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(s,e)}Ro.p2wsh=P6;var oi={},nn={};Object.defineProperty(nn,"__esModule",{value:!0});nn.getEccLib=nn.initEccLib=void 0;const wi={};function T6(e,t){e?e!==wi.eccLib&&(t!=null&&t.DANGER_DO_NOT_VERIFY_ECCLIB||k6(e),wi.eccLib=e):wi.eccLib=e}nn.initEccLib=T6;function I6(){if(!wi.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return wi.eccLib}nn.getEccLib=I6;const tr=e=>Buffer.from(e,"hex");function k6(e){yt(typeof e.isXOnlyPoint=="function"),yt(e.isXOnlyPoint(tr("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),yt(e.isXOnlyPoint(tr("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),yt(e.isXOnlyPoint(tr("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),yt(e.isXOnlyPoint(tr("0000000000000000000000000000000000000000000000000000000000000001"))),yt(!e.isXOnlyPoint(tr("0000000000000000000000000000000000000000000000000000000000000000"))),yt(!e.isXOnlyPoint(tr("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),yt(typeof e.xOnlyPointAddTweak=="function"),B6.forEach(t=>{const r=e.xOnlyPointAddTweak(tr(t.pubkey),tr(t.tweak));t.result===null?yt(r===null):(yt(r!==null),yt(r.parity===t.parity),yt(Buffer.from(r.xOnlyPubkey).equals(tr(t.result))))})}function yt(e){if(!e)throw new Error("ecc library invalid")}const B6=[{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 df={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.tweakKey=e.tapTweakHash=e.tapleafHash=e.findScriptPath=e.toHashTree=e.rootHashFromPath=e.MAX_TAPTREE_DEPTH=e.LEAF_VERSION_TAPSCRIPT=void 0;const t=un,r=nn,n=Nr,i=Le,s=qe;e.LEAF_VERSION_TAPSCRIPT=192,e.MAX_TAPTREE_DEPTH=128;const o=b=>"left"in b&&"right"in b;function a(b,E){if(b.length<33)throw new TypeError(`The control-block length is too small. Got ${b.length}, expected min 33.`);const A=(b.length-33)/32;let P=E;for(let w=0;w<A;w++){const _=b.slice(33+32*w,65+32*w);P.compare(_)<0?P=p(P,_):P=p(_,P)}return P}e.rootHashFromPath=a;function c(b){if((0,s.isTapleaf)(b))return{hash:u(b)};const E=[c(b[0]),c(b[1])];E.sort((w,_)=>w.hash.compare(_.hash));const[A,P]=E;return{hash:p(A.hash,P.hash),left:A,right:P}}e.toHashTree=c;function f(b,E){if(o(b)){const A=f(b.left,E);if(A!==void 0)return[...A,b.right.hash];const P=f(b.right,E);if(P!==void 0)return[...P,b.left.hash]}else if(b.hash.equals(E))return[]}e.findScriptPath=f;function u(b){const E=b.version||e.LEAF_VERSION_TAPSCRIPT;return n.taggedHash("TapLeaf",t.Buffer.concat([t.Buffer.from([E]),g(b.output)]))}e.tapleafHash=u;function d(b,E){return n.taggedHash("TapTweak",t.Buffer.concat(E?[b,E]:[b]))}e.tapTweakHash=d;function y(b,E){if(!t.Buffer.isBuffer(b)||b.length!==32||E&&E.length!==32)return null;const A=d(b,E),P=(0,r.getEccLib)().xOnlyPointAddTweak(b,A);return!P||P.xOnlyPubkey===null?null:{parity:P.parity,x:t.Buffer.from(P.xOnlyPubkey)}}e.tweakKey=y;function p(b,E){return n.taggedHash("TapBranch",t.Buffer.concat([b,E]))}function g(b){const E=i.varuint.encodingLength(b.length),A=t.Buffer.allocUnsafe(E);return i.varuint.encode(b.length,A),t.Buffer.concat([A,b])}})(df);var Ye={},Ld;function O6(){if(Ld)return Ye;Ld=1,Object.defineProperty(Ye,"__esModule",{value:!0}),Ye.toOutputScript=Ye.fromOutputScript=Ye.toBech32=Ye.toBase58Check=Ye.fromBech32=Ye.fromBase58Check=void 0;const e=ze,t=lf(),r=pt(),n=qe,i=dr,s=uf,o=40,a=2,c=16,f=2,u=80,d="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 y(w,_){const T=w.slice(2);if(T.length<a||T.length>o)throw new TypeError("Invalid program length for segwit address");const I=w[0]-u;if(I<f||I>c)throw new TypeError("Invalid version for segwit address");if(w[1]!==T.length)throw new TypeError("Invalid script for segwit address");return console.warn(d),E(T,I,_.bech32)}function p(w){const _=Buffer.from(s.decode(w));if(_.length<21)throw new TypeError(w+" is too short");if(_.length>21)throw new TypeError(w+" is too long");const T=_.readUInt8(0),I=_.slice(1);return{version:T,hash:I}}Ye.fromBase58Check=p;function g(w){let _,T;try{_=i.bech32.decode(w)}catch{}if(_){if(T=_.words[0],T!==0)throw new TypeError(w+" uses wrong encoding")}else if(_=i.bech32m.decode(w),T=_.words[0],T===0)throw new TypeError(w+" uses wrong encoding");const I=i.bech32.fromWords(_.words.slice(1));return{version:T,prefix:_.prefix,data:Buffer.from(I)}}Ye.fromBech32=g;function b(w,_){(0,n.typeforce)((0,n.tuple)(n.Hash160bit,n.UInt8),arguments);const T=Buffer.allocUnsafe(21);return T.writeUInt8(_,0),w.copy(T,1),s.encode(T)}Ye.toBase58Check=b;function E(w,_,T){const I=i.bech32.toWords(w);return I.unshift(_),_===0?i.bech32.encode(T,I):i.bech32m.encode(T,I)}Ye.toBech32=E;function A(w,_){_=_||e.bitcoin;try{return t.p2pkh({output:w,network:_}).address}catch{}try{return t.p2sh({output:w,network:_}).address}catch{}try{return t.p2wpkh({output:w,network:_}).address}catch{}try{return t.p2wsh({output:w,network:_}).address}catch{}try{return t.p2tr({output:w,network:_}).address}catch{}try{return y(w,_)}catch{}throw new Error(r.toASM(w)+" has no matching Address")}Ye.fromOutputScript=A;function P(w,_){_=_||e.bitcoin;let T,I;try{T=p(w)}catch{}if(T){if(T.version===_.pubKeyHash)return t.p2pkh({hash:T.hash}).output;if(T.version===_.scriptHash)return t.p2sh({hash:T.hash}).output}else{try{I=g(w)}catch{}if(I){if(I.prefix!==_.bech32)throw new Error(w+" has an invalid prefix");if(I.version===0){if(I.data.length===20)return t.p2wpkh({hash:I.data}).output;if(I.data.length===32)return t.p2wsh({hash:I.data}).output}else if(I.version===1){if(I.data.length===32)return t.p2tr({pubkey:I.data}).output}else if(I.version>=f&&I.version<=c&&I.data.length>=a&&I.data.length<=o)return console.warn(d),r.compile([I.version+u,I.data])}}throw new Error(w+" has no matching Script")}return Ye.toOutputScript=P,Ye}var Md;function C6(){if(Md)return oi;Md=1,Object.defineProperty(oi,"__esModule",{value:!0}),oi.p2tr=void 0;const e=un,t=ze,r=pt(),n=qe,i=nn,s=df,o=ft,a=dr,c=O6(),f=r.OPS,u=1,d=80;function y(p,g){if(!p.address&&!p.output&&!p.pubkey&&!p.internalPubkey&&!(p.witness&&p.witness.length>1))throw new TypeError("Not enough data");g=Object.assign({validate:!0},g||{}),(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)},p);const b=o.value(()=>(0,c.fromBech32)(p.address)),E=o.value(()=>{if(!(!p.witness||!p.witness.length))return p.witness.length>=2&&p.witness[p.witness.length-1][0]===d?p.witness.slice(0,-1):p.witness.slice()}),A=o.value(()=>{if(p.scriptTree)return(0,s.toHashTree)(p.scriptTree);if(p.hash)return{hash:p.hash}}),P=p.network||t.bitcoin,w={name:"p2tr",network:P};if(o.prop(w,"address",()=>{if(!w.pubkey)return;const _=a.bech32m.toWords(w.pubkey);return _.unshift(u),a.bech32m.encode(P.bech32,_)}),o.prop(w,"hash",()=>{const _=A();if(_)return _.hash;const T=E();if(T&&T.length>1){const I=T[T.length-1],R=I[0]&n.TAPLEAF_VERSION_MASK,L=T[T.length-2],S=(0,s.tapleafHash)({output:L,version:R});return(0,s.rootHashFromPath)(I,S)}return null}),o.prop(w,"output",()=>{if(w.pubkey)return r.compile([f.OP_1,w.pubkey])}),o.prop(w,"redeemVersion",()=>p.redeemVersion?p.redeemVersion:p.redeem&&p.redeem.redeemVersion!==void 0&&p.redeem.redeemVersion!==null?p.redeem.redeemVersion:s.LEAF_VERSION_TAPSCRIPT),o.prop(w,"redeem",()=>{const _=E();if(!(!_||_.length<2))return{output:_[_.length-2],witness:_.slice(0,-2),redeemVersion:_[_.length-1][0]&n.TAPLEAF_VERSION_MASK}}),o.prop(w,"pubkey",()=>{if(p.pubkey)return p.pubkey;if(p.output)return p.output.slice(2);if(p.address)return b().data;if(w.internalPubkey){const _=(0,s.tweakKey)(w.internalPubkey,w.hash);if(_)return _.x}}),o.prop(w,"internalPubkey",()=>{if(p.internalPubkey)return p.internalPubkey;const _=E();if(_&&_.length>1)return _[_.length-1].slice(1,33)}),o.prop(w,"signature",()=>{if(p.signature)return p.signature;const _=E();if(!(!_||_.length!==1))return _[0]}),o.prop(w,"witness",()=>{if(p.witness)return p.witness;const _=A();if(_&&p.redeem&&p.redeem.output&&p.internalPubkey){const T=(0,s.tapleafHash)({output:p.redeem.output,version:w.redeemVersion}),I=(0,s.findScriptPath)(_,T);if(!I)return;const R=(0,s.tweakKey)(p.internalPubkey,_.hash);if(!R)return;const L=e.Buffer.concat([e.Buffer.from([w.redeemVersion|R.parity]),p.internalPubkey].concat(I));return[p.redeem.output,L]}if(p.signature)return[p.signature]}),g.validate){let _=e.Buffer.from([]);if(p.address){if(P&&P.bech32!==b().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(b().version!==u)throw new TypeError("Invalid address version");if(b().data.length!==32)throw new TypeError("Invalid address data");_=b().data}if(p.pubkey){if(_.length>0&&!_.equals(p.pubkey))throw new TypeError("Pubkey mismatch");_=p.pubkey}if(p.output){if(p.output.length!==34||p.output[0]!==f.OP_1||p.output[1]!==32)throw new TypeError("Output is invalid");if(_.length>0&&!_.equals(p.output.slice(2)))throw new TypeError("Pubkey mismatch");_=p.output.slice(2)}if(p.internalPubkey){const R=(0,s.tweakKey)(p.internalPubkey,w.hash);if(_.length>0&&!_.equals(R.x))throw new TypeError("Pubkey mismatch");_=R.x}if(_&&_.length&&!(0,i.getEccLib)().isXOnlyPoint(_))throw new TypeError("Invalid pubkey for p2tr");const T=A();if(p.hash&&T&&!p.hash.equals(T.hash))throw new TypeError("Hash mismatch");if(p.redeem&&p.redeem.output&&T){const R=(0,s.tapleafHash)({output:p.redeem.output,version:w.redeemVersion});if(!(0,s.findScriptPath)(T,R))throw new TypeError("Redeem script not in tree")}const I=E();if(p.redeem&&w.redeem){if(p.redeem.redeemVersion&&p.redeem.redeemVersion!==w.redeem.redeemVersion)throw new TypeError("Redeem.redeemVersion and witness mismatch");if(p.redeem.output){if(r.decompile(p.redeem.output).length===0)throw new TypeError("Redeem.output is invalid");if(w.redeem.output&&!p.redeem.output.equals(w.redeem.output))throw new TypeError("Redeem.output and witness mismatch")}if(p.redeem.witness&&w.redeem.witness&&!(0,n.stacksEqual)(p.redeem.witness,w.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(I&&I.length)if(I.length===1){if(p.signature&&!p.signature.equals(I[0]))throw new TypeError("Signature mismatch")}else{const R=I[I.length-1];if(R.length<33)throw new TypeError(`The control-block length is too small. Got ${R.length}, expected min 33.`);if((R.length-33)%32!==0)throw new TypeError(`The control-block length of ${R.length} is incorrect!`);const L=(R.length-33)/32;if(L>128)throw new TypeError(`The script path is too long. Got ${L}, expected max 128.`);const S=R.slice(1,33);if(p.internalPubkey&&!p.internalPubkey.equals(S))throw new TypeError("Internal pubkey mismatch");if(!(0,i.getEccLib)().isXOnlyPoint(S))throw new TypeError("Invalid internalPubkey for p2tr witness");const $=R[0]&n.TAPLEAF_VERSION_MASK,C=I[I.length-2],U=(0,s.tapleafHash)({output:C,version:$}),j=(0,s.rootHashFromPath)(R,U),V=(0,s.tweakKey)(S,j);if(!V)throw new TypeError("Invalid outputKey for p2tr witness");if(_.length&&!_.equals(V.x))throw new TypeError("Pubkey mismatch for p2tr witness");if(V.parity!==(R[0]&1))throw new Error("Incorrect parity")}}return Object.assign(w,p)}return oi.p2tr=y,oi}var Dd;function lf(){return Dd||(Dd=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.p2tr=e.p2wsh=e.p2wpkh=e.p2sh=e.p2pkh=e.p2pk=e.p2ms=e.embed=void 0;const t=To;Object.defineProperty(e,"embed",{enumerable:!0,get:function(){return t.p2data}});const r=Io;Object.defineProperty(e,"p2ms",{enumerable:!0,get:function(){return r.p2ms}});const n=ko;Object.defineProperty(e,"p2pk",{enumerable:!0,get:function(){return n.p2pk}});const i=Bo;Object.defineProperty(e,"p2pkh",{enumerable:!0,get:function(){return i.p2pkh}});const s=Oo;Object.defineProperty(e,"p2sh",{enumerable:!0,get:function(){return s.p2sh}});const o=Co;Object.defineProperty(e,"p2wpkh",{enumerable:!0,get:function(){return o.p2wpkh}});const a=Ro;Object.defineProperty(e,"p2wsh",{enumerable:!0,get:function(){return a.p2wsh}});const c=C6();Object.defineProperty(e,"p2tr",{enumerable:!0,get:function(){return c.p2tr}})}(ua)),ua}Object.defineProperty(me,"__esModule",{value:!0});me.signatureBlocksAction=me.checkInputForSig=me.pubkeyInScript=me.pubkeyPositionInScript=me.witnessStackToScriptWitness=me.isP2TR=me.isP2SHScript=me.isP2WSHScript=me.isP2WPKH=me.isP2PKH=me.isP2PK=me.isP2MS=void 0;const jd=ds,vi=pt(),Bs=fs,R6=Nr,fn=lf();function dn(e){return t=>{try{return e({output:t}),!0}catch{return!1}}}me.isP2MS=dn(fn.p2ms);me.isP2PK=dn(fn.p2pk);me.isP2PKH=dn(fn.p2pkh);me.isP2WPKH=dn(fn.p2wpkh);me.isP2WSHScript=dn(fn.p2wsh);me.isP2SHScript=dn(fn.p2sh);me.isP2TR=dn(fn.p2tr);function N6(e){let t=Buffer.allocUnsafe(0);function r(o){t=Buffer.concat([t,Buffer.from(o)])}function n(o){const a=t.length,c=jd.encodingLength(o);t=Buffer.concat([t,Buffer.allocUnsafe(c)]),jd.encode(o,t,a)}function i(o){n(o.length),r(o)}function s(o){n(o.length),o.forEach(i)}return s(e),t}me.witnessStackToScriptWitness=N6;function ay(e,t){const r=(0,R6.hash160)(e),n=e.slice(1,33),i=vi.decompile(t);if(i===null)throw new Error("Unknown script error");return i.findIndex(s=>typeof s=="number"?!1:s.equals(e)||s.equals(r)||s.equals(n))}me.pubkeyPositionInScript=ay;function F6(e,t){return ay(e,t)!==-1}me.pubkeyInScript=F6;function $6(e,t){return U6(e).some(n=>cy(n,vi.signature.decode,t))}me.checkInputForSig=$6;function cy(e,t,r){const{hashType:n}=t(e),i=[];switch(n&Bs.Transaction.SIGHASH_ANYONECANPAY&&i.push("addInput"),n&31){case Bs.Transaction.SIGHASH_ALL:break;case Bs.Transaction.SIGHASH_SINGLE:case Bs.Transaction.SIGHASH_NONE:i.push("addOutput"),i.push("setInputSequence");break}return i.indexOf(r)===-1}me.signatureBlocksAction=cy;function U6(e){let t=[];if((e.partialSig||[]).length===0){if(!e.finalScriptSig&&!e.finalScriptWitness)return[];t=H6(e)}else t=e.partialSig;return t.map(r=>r.signature)}function H6(e){const t=e.finalScriptSig?vi.decompile(e.finalScriptSig)||[]:[],r=e.finalScriptWitness?vi.decompile(e.finalScriptWitness)||[]:[];return t.concat(r).filter(n=>Buffer.isBuffer(n)&&vi.isCanonicalScriptSignature(n)).map(n=>({signature:n}))}Object.defineProperty(_e,"__esModule",{value:!0});_e.checkTaprootInputForSigs=_e.tapTreeFromList=_e.tapTreeToList=_e.tweakInternalPubKey=_e.checkTaprootOutputFields=_e.checkTaprootInputFields=_e.isTaprootOutput=_e.isTaprootInput=hi=_e.serializeTaprootSignature=_e.tapScriptFinalizer=_e.toXOnly=void 0;const pf=qe,L6=fs,No=me,Rr=df,M6=lf(),D6=me,j6=e=>e.length===32?e:e.slice(1,33);_e.toXOnly=j6;function z6(e,t,r){const n=ax(t,e,r);try{const s=sx(t,n).concat(n.script).concat(n.controlBlock);return{finalScriptWitness:(0,No.witnessStackToScriptWitness)(s)}}catch(i){throw new Error(`Can not finalize taproot input #${e}: ${i}`)}}_e.tapScriptFinalizer=z6;function q6(e,t){const r=t?Buffer.from([t]):Buffer.from([]);return Buffer.concat([e,r])}var hi=_e.serializeTaprootSignature=q6;function js(e){return e&&!!(e.tapInternalKey||e.tapMerkleRoot||e.tapLeafScript&&e.tapLeafScript.length||e.tapBip32Derivation&&e.tapBip32Derivation.length||e.witnessUtxo&&(0,No.isP2TR)(e.witnessUtxo.script))}_e.isTaprootInput=js;function zs(e,t){return e&&!!(e.tapInternalKey||e.tapTree||e.tapBip32Derivation&&e.tapBip32Derivation.length||t&&(0,No.isP2TR)(t))}_e.isTaprootOutput=zs;function G6(e,t,r){rx(e,t,r),ix(e,t,r)}_e.checkTaprootInputFields=G6;function V6(e,t,r){nx(e,t,r),W6(e,t)}_e.checkTaprootOutputFields=V6;function W6(e,t){if(!t.tapTree&&!t.tapInternalKey)return;const r=t.tapInternalKey||e.tapInternalKey,n=t.tapTree||e.tapTree;if(r){const{script:i}=e,s=K6(r,n);if(i&&!i.equals(s))throw new Error("Error adding output. Script or address missmatch.")}}function K6(e,t){const r=t&&uy(t.leaves),{output:n}=(0,M6.p2tr)({internalPubkey:e,scriptTree:r});return n}function Y6(e,t){const r=t.tapInternalKey,n=r&&(0,Rr.tweakKey)(r,t.tapMerkleRoot);if(!n)throw new Error(`Cannot tweak tap internal key for input #${e}. Public key: ${r&&r.toString("hex")}`);return n.x}_e.tweakInternalPubKey=Y6;function Z6(e){if(!(0,pf.isTaptree)(e))throw new Error("Cannot convert taptree to tapleaf list. Expecting a tapree structure.");return su(e)}_e.tapTreeToList=Z6;function uy(e=[]){return e.length===1&&e[0].depth===0?{output:e[0].script,version:e[0].leafVersion}:tx(e)}_e.tapTreeFromList=uy;function X6(e,t){return Q6(e).some(n=>(0,D6.signatureBlocksAction)(n,J6,t))}_e.checkTaprootInputForSigs=X6;function J6(e){return{signature:e.slice(0,64),hashType:e.slice(64)[0]||L6.Transaction.SIGHASH_DEFAULT}}function Q6(e){const t=[];if(e.tapKeySig&&t.push(e.tapKeySig),e.tapScriptSig&&t.push(...e.tapScriptSig.map(r=>r.signature)),!t.length){const r=ex(e.finalScriptWitness);r&&t.push(r)}return t}function ex(e){if(!e)return;const t=e.slice(2);if(t.length===64||t.length===65)return t}function su(e,t=[],r=0){if(r>Rr.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return e?(0,pf.isTapleaf)(e)?(t.push({depth:r,leafVersion:e.version||Rr.LEAF_VERSION_TAPSCRIPT,script:e.output}),t):(e[0]&&su(e[0],t,r+1),e[1]&&su(e[1],t,r+1),t):[]}function tx(e){let t;for(const r of e)if(t=ou(r,t),!t)throw new Error("No room left to insert tapleaf in tree");return t}function ou(e,t,r=0){if(r>Rr.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");if(e.depth===r)return t?void 0:{output:e.script,version:e.leafVersion};if((0,pf.isTapleaf)(t))return;const n=ou(e,t&&t[0],r+1);if(n)return[n,t&&t[1]];const i=ou(e,t&&t[1],r+1);if(i)return[t&&t[0],i]}function rx(e,t,r){const n=js(e)&&On(t),i=On(e)&&js(t),s=e===t&&js(t)&&On(t);if(n||i||s)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function nx(e,t,r){const n=zs(e)&&On(t),i=On(e)&&zs(t),s=e===t&&zs(t)&&On(t);if(n||i||s)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function ix(e,t,r){if(t.tapMerkleRoot){const n=(t.tapLeafScript||[]).every(s=>ha(s,t.tapMerkleRoot)),i=(e.tapLeafScript||[]).every(s=>ha(s,t.tapMerkleRoot));if(!n||!i)throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}else if(e.tapMerkleRoot&&!(t.tapLeafScript||[]).every(i=>ha(i,e.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}function ha(e,t){if(!t)return!0;const r=(0,Rr.tapleafHash)({output:e.script,version:e.leafVersion});return(0,Rr.rootHashFromPath)(e.controlBlock,r).equals(t)}function sx(e,t){const r=(0,Rr.tapleafHash)({output:t.script,version:t.leafVersion});return(e.tapScriptSig||[]).filter(n=>n.leafHash.equals(r)).map(n=>ox(t.script,n)).sort((n,i)=>i.positionInScript-n.positionInScript).map(n=>n.signature)}function ox(e,t){return Object.assign({positionInScript:(0,No.pubkeyPositionInScript)(t.pubkey,e)},t)}function ax(e,t,r){if(!e.tapScriptSig||!e.tapScriptSig.length)throw new Error(`Can not finalize taproot input #${t}. No tapleaf script signature provided.`);const n=(e.tapLeafScript||[]).sort((i,s)=>i.controlBlock.length-s.controlBlock.length).find(i=>cx(i,e.tapScriptSig,r));if(!n)throw new Error(`Can not finalize taproot input #${t}. Signature for tapleaf script not found.`);return n}function cx(e,t,r){const n=(0,Rr.tapleafHash)({output:e.script,version:e.leafVersion});return(!r||r.equals(n))&&t.find(s=>s.leafHash.equals(n))!==void 0}function On(e){return e&&!!(e.redeemScript||e.witnessScript||e.bip32Derivation&&e.bip32Derivation.length)}const Ze={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:e=>"counterparty signature not found for utxo "+e,invalidCounterpartySigForUTXO:e=>"invalid counterparty signature for utxo "+e,htlcNotExpired:e=>`HTLC not expired, need more ${e} blocks`,controlBlockGenerationFailed:"failed to generate control block",invalidLeaf:"invalid leaf"},Os=192;pe.initEccLib(wt);class Ei{constructor(t,r,n,i,s,o,a,c){this.secretHash=n,this.redeemerPubkey=i,this.initiatorPubkey=s,this.expiry=o,this.signer=t,this.network=a,this.internalPubkey=aE(),this.initiateAmount=r,this.utxoHashes=c}static async from(t,r,n,i,s,o,a){n=n.startsWith("0x")?n.slice(2):n,yn(n.length===64,Ze.secretHashLenMismatch),yn(i.length===64||i.length===66,`initiator ${Ze.pubkeyLenMismatch}`),yn(s.length===64||s.length===66,`redeemer ${Ze.pubkeyLenMismatch}`),yn(o>0,Ze.zeroOrNegativeExpiry);const c=await t.getNetwork();return new Ei(t,r,n,Qc(s).toString("hex"),Qc(i).toString("hex"),o,c,a)}address(){const{address:t}=pe.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves()});if(!t)throw new Error(Ze.htlcAddressGenerationFailed);return t}id(){return this.address()}async _buildRawTx(t,r){const n=new pe.Transaction;n.version=2;const i=this.address(),s=await this.signer.getProvider();let o=[];if(this.utxoHashes&&this.utxoHashes.length>0)for(const f of this.utxoHashes){const u=await s.getTransaction(f);for(let d=0;d<u.vout.length;d++){const y=u.vout[d];y.scriptpubkey_address===i&&o.push({txid:u.txid,vout:d,value:y.value,status:{confirmed:!1}})}}else o=await s.getUTXOs(i);const a=o.reduce((f,u)=>f+u.value,0);if(a===0)throw new Error(`${i} ${Ze.notFunded}`);for(let f=0;f<o.length;f++)n.addInput(Buffer.from(o[f].txid,"hex").reverse(),o[f].vout);if(r!=null&&r.vSize){const f=await s.getFeeRates(),u=Math.ceil(f.hourFee*r.vSize),d=a-u;return n.addOutput(pe.address.toOutputScript(t,this.network),d),{tx:n,usedUtxos:o}}const c=(r==null?void 0:r.fee)??await s.suggestFee(i,a,In.MEDIUM);return n.addOutput(pe.address.toOutputScript(t,this.network),a-c),{tx:n,usedUtxos:o,fee:c,balance:a}}getOutputScript(){return pe.address.toOutputScript(this.address(),this.network)}async init(t){return t??(t=await(await this.signer.getProvider()).suggestFee(await this.signer.getAddress(),this.initiateAmount,In.MEDIUM)),await this.signer.send(this.address(),this.initiateAmount,t)}async generateRedeemSACP(t,r,n){const{tx:i,usedUtxos:s}=await this._buildRawTx(r,{fee:n}),o=this.getOutputScript(),a=pe.Transaction.SIGHASH_SINGLE|pe.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(1),f=s.map(d=>d.value),u=ai(o,s.length);for(let d=0;d<i.ins.length;d++){const y=i.hashForWitnessV1(d,u,f,a,c),p=await this.signer.signSchnorr(y);i.setWitness(d,[hi(p,a),Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}return i.toHex()}async generateInstantRefundSACP(t){const r=this.getOutputScript(),{tx:n,usedUtxos:i,fee:s}=await this._buildRawTx(t,{fee:0});n.outs=[];const o=Math.max(...i.map(d=>d.value));i.forEach(({value:d})=>{n.addOutput(r,d-(d===o?s??0:0))});const a=pe.Transaction.SIGHASH_SINGLE|pe.Transaction.SIGHASH_ANYONECANPAY,c=this.leafHash(2),f=i.map(d=>d.value),u=ai(r,i.length);for(let d=0;d<n.ins.length;d++){const y=n.hashForWitnessV1(d,u,f,a,c),p=await this.signer.signSchnorr(y);n.setWitness(d,[hi(p,a),hi(p,a),this.instantRefundLeaf(),this.generateControlBlockFor(2)])}return n.toHex()}async generateInstantRefundSACPWithHash(t){const r=[],n=pe.Transaction.SIGHASH_SINGLE|pe.Transaction.SIGHASH_ANYONECANPAY;for(let i=0;i<t.length;i++){const s=Buffer.from(t[i],"hex"),o=await this.signer.signSchnorr(s);r.push(hi(o,n).toString("hex"))}return r}async instantRefund(t,r){yn(t.length>0,Ze.noCounterpartySigs);const{tx:n,usedUtxos:i}=await this._buildRawTx(await this.signer.getAddress(),{fee:r});for(const d of i)if(!t.find(y=>y.utxo===d.txid))throw new Error(Ze.counterPartySigNotFound(d.txid));const s=this.getOutputScript(),o=pe.Transaction.SIGHASH_DEFAULT,a=this.leafHash(2),c=i.map(d=>d.value),f=ai(s,i.length);for(let d=0;d<n.ins.length;d++){const y=n.hashForWitnessV1(d,f,c,o,a);if(!wt.verifySchnorr(y,Buffer.from(this.redeemerPubkey,"hex"),Buffer.from(t[d].sig,"hex")))throw new Error(Ze.invalidCounterpartySigForUTXO(t[d].utxo));const p=await this.signer.signSchnorr(y),g=Buffer.from(n.ins[d].hash).reverse().toString("hex"),b=t.find(E=>E.utxo===g);if(!b)throw new Error(Ze.counterPartySigNotFound(g));n.setWitness(d,[Buffer.from(b.sig,"hex"),p,this.instantRefundLeaf(),this.generateControlBlockFor(2)])}return await(await this.signer.getProvider()).broadcast(n.toHex())}async redeem(t,r){const n=await this.getRedeemHex(t,r);return await(await this.signer.getProvider()).broadcast(n)}async getRedeemHex(t,r){yn(pe.crypto.sha256(Buffer.from(t,"hex")).toString("hex")===this.secretHash,Ze.secretMismatch);const n=r??await this.signer.getAddress(),{tx:i,usedUtxos:s}=await this._buildRawTx(n,{fee:0}),o=this.leafHash(1),a=s.map(d=>d.value),c=ai(this.getOutputScript(),s.length),f=pe.Transaction.SIGHASH_DEFAULT;for(let d=0;d<i.ins.length;d++){const y=i.hashForWitnessV1(d,c,a,f,o),p=await this.signer.signSchnorr(y);i.setWitness(d,[p,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}const{tx:u}=await this._buildRawTx(n,{vSize:i.virtualSize()});for(let d=0;d<u.ins.length;d++){const y=u.hashForWitnessV1(d,c,a,f,o),p=await this.signer.signSchnorr(y);u.setWitness(d,[p,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}return u.toHex()}async refund(t,r){const{tx:n,usedUtxos:i}=await this._buildRawTx(t??await this.signer.getAddress(),{fee:r}),[s,o]=await this.canRefund(i);if(!s)throw new Error(Ze.htlcNotExpired(o));const a=this.leafHash(0),c=i.map(y=>y.value),f=ai(this.getOutputScript(),i.length),u=pe.Transaction.SIGHASH_DEFAULT;for(let y=0;y<n.ins.length;y++){n.ins[y].sequence=this.expiry;const p=n.hashForWitnessV1(y,f,c,u,a),g=await this.signer.signSchnorr(p);n.setWitness(y,[g,this.refundLeaf(),this.generateControlBlockFor(0)])}return await(await this.signer.getProvider()).broadcast(n.toHex())}async canRefund(t){const n=await(await this.signer.getProvider()).getLatestTip();for(const i of t){let s=0;if(i.status.confirmed&&i.status.block_height+this.expiry>n?s=i.status.block_height+this.expiry-n+1:i.status.confirmed||(s=this.expiry+1),s>0)return[!1,s]}return[!0,0]}generateControlBlockFor(t){let r;switch(t){case 1:r=this.redeemLeaf();break;case 0:r=this.refundLeaf();break;case 2:r=this.instantRefundLeaf();break;default:throw new Error(Ze.invalidLeaf)}const n=pe.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves(),redeem:{output:r,redeemVersion:Os}});if(!n.witness)throw new Error(Ze.controlBlockGenerationFailed);return n.witness[n.witness.length-1]}leafHash(t){let r=this.redeemLeaf();return t===0&&(r=this.refundLeaf()),t===2&&(r=this.instantRefundLeaf()),pe.crypto.taggedHash("TapLeaf",Wv(r))}refundLeaf(){return pe.script.fromASM(`
54
54
  ${pe.script.number.encode(this.expiry).toString("hex")}
55
55
  OP_CHECKSEQUENCEVERIFY
56
56
  OP_DROP
@@ -69,7 +69,7 @@ ${tb(p)}`),super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessa
69
69
  OP_CHECKSIGADD
70
70
  OP_2
71
71
  OP_NUMEQUAL
72
- `.trim().replace(/\s+/g," "))}leaves(){return[{version:Os,output:this.redeemLeaf()},[{version:Os,output:this.refundLeaf()},{version:Os,output:this.instantRefundLeaf()}]]}generateMerkleProofFor(t){const r=this.leafHash(1),n=this.leafHash(2),i=this.leafHash(0);switch(t){case 1:{const s=Yv(i,n);return[pe.crypto.taggedHash("TapBranch",Buffer.concat(s))]}case 0:return[n,r];case 2:return[i,r];default:throw new Error(Ze.invalidLeaf)}}}function ai(e,t){const r=[];for(let n=0;n<t;n++)r.push(e);return r}class ux{constructor(){this.cache={}}set(t,r,n,i){const s={txHash:n,timeStamp:Date.now(),btcRedeemUTXO:i};this.cache[`${r}_${t.create_order.create_id}`]=s}get(t,r){return this.cache[`${r}_${t.create_order.create_id}`]||null}remove(t,r){delete this.cache[`${r}_${t.create_order.create_id}`]}}class fx{constructor(){this.cache={}}set(t,r){this.cache[t]=r}get(t){return this.cache[t]||null}}class fy{constructor(t,r){this.url=new x.Url(t).endpoint("blocknumbers").endpoint(r)}async fetchBlockNumbers(){try{const t=await x.Fetcher.get(this.url);return x.Ok(t)}catch(t){return x.Err("Failed to fetch block numbers",t)}}}class dy{constructor(t){this.quoteUrl=new x.Url(t)}async getQuoteFromAssets({fromAsset:t,toAsset:r,amount:n,isExactOut:i=!1,options:s}){const o=eu(t.chain,t.atomicSwapAddress,r.chain,r.atomicSwapAddress);return this.getQuote(o,n,i,s)}async getQuote(t,r,n=!1,i){try{const s={order_pair:t,amount:r.toString(),exact_out:n.toString(),...(i==null?void 0:i.affiliateFee)!==void 0&&{affiliate_fee:i.affiliateFee.toString()}},o=this.quoteUrl.endpoint("/").addSearchParams(s),a=await x.Fetcher.get(o,{retryCount:0,...i==null?void 0:i.request});return a.error?x.Err(a.error):a.result?x.Ok(a.result):x.Err("GetQuote: Unexpected error, result is undefined")}catch(s){return x.Err("GetQuote:",String(s))}}async getAttestedQuote(t){try{const r=await x.Fetcher.post(this.quoteUrl.endpoint("/attested").toString(),{body:JSON.stringify(t),headers:{"Content-Type":"application/json"}});return r.error?x.Err(r.error):r.result?x.Ok(r.result):x.Err("GetAttestedQuote: Unexpected error, result is undefined")}catch(r){return console.log("error :",r),x.Err("GetAttestedQuote:",String(r))}}async getStrategies(){try{const t=await x.Fetcher.get(this.quoteUrl.endpoint("/strategies"));if(t.error)return x.Err(t.error);if(!t.result)return x.Err("GetStrategies: Unexpected error, result is undefined");const r={};for(const n of Object.values(t.result)){const i=eu(n.source_chain,n.source_asset.asset,n.dest_chain,n.dest_asset.asset);r[i]={id:n.id,minAmount:n.min_amount,maxAmount:n.max_amount,fee:n.fee,fixed_fee:Number(n.fixed_fee)}}return x.Ok(r)}catch(t){return x.Err("GetStrategies:",String(t))}}}class Xi extends x.EventBroker{get isInitialized(){return!!this.digestKey}constructor(t,r){super(),this.digestKey=t,this.walletClient=r}static fromDigestKey(t){return new Xi(x.trim0x(t))}static fromWalletClient(t){return new Xi(void 0,t)}async initialize(){if(this.digestKey)return x.Ok("Already initialized");const t=await this.deriveDigestKeyFromWalletClient();return t.error?x.Err(t.error):(this.emit("initialized",!0),x.Ok("Initialized"))}async deriveDigestKeyFromWalletClient(){if(!this.walletClient)return x.Err("No walletClient found");if(!this.walletClient.account)return x.Err("No account found");try{const t=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=x.trim0x(di(t)),this.emit("initialized",!0),x.Ok(this.digestKey)}catch(t){return x.Err("Failed to initialize: "+t)}}async getDigestKey(){if(!this.digestKey&&!this.walletClient)return x.Err("No private key or wallet client found");if(!this.digestKey&&this.walletClient){const t=await this.deriveDigestKeyFromWalletClient();if(t.error)return x.Err(t.error)}return this.digestKey?x.Ok(this.digestKey):x.Err("No private key found")}async generateSecret(t){const r=await this.signMessage(t);if(!r.ok)return x.Err(r.error);const n=di(x.with0x(r.val)),i=di(n);return x.Ok({secret:n,secretHash:i})}async signMessage(t){if(!this.digestKey){const f=await this.getDigestKey();if(!f.ok)return x.Err(f.error);this.digestKey=f.val}const r=Fs.ECPairFactory(bt),n="Garden.fi"+t.toString(),i=Buffer.from(n,"utf8"),s=di(i),o=Buffer.from(x.trim0x(this.digestKey),"hex");if(o.length!==32)return x.Err("Invalid private key length. Expected 32 bytes.");const c=r.fromPrivateKey(o).sign(Buffer.from(x.trim0x(s),"hex"));return x.Ok(c.toString("hex"))}}const zd=[{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"}],dx={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}},lx={block:kb({format(e){var r;return{transactions:(r=e.transactions)==null?void 0:r.map(n=>{if(typeof n=="string")return n;const i=fo(n);return i.typeHex==="0x7e"&&(i.isSystemTx=n.isSystemTx,i.mint=n.mint?Ue(n.mint):void 0,i.sourceHash=n.sourceHash,i.type="deposit"),i}),stateRoot:e.stateRoot}}}),transaction:Tb({format(e){const t={};return e.type==="0x7e"&&(t.isSystemTx=e.isSystemTx,t.mint=e.mint?Ue(e.mint):void 0,t.sourceHash=e.sourceHash,t.type="deposit"),t}}),transactionReceipt:Hw({format(e){return{l1GasPrice:e.l1GasPrice?Ue(e.l1GasPrice):null,l1GasUsed:e.l1GasUsed?Ue(e.l1GasUsed):null,l1Fee:e.l1Fee?Ue(e.l1Fee):null,l1FeeScalar:e.l1FeeScalar?Number(e.l1FeeScalar):null}}})};function px(e,t){return mx(e)?yx(e):H1(e,t)}const hx={transaction:px};function yx(e){gx(e);const{sourceHash:t,data:r,from:n,gas:i,isSystemTx:s,mint:o,to:a,value:c}=e,f=[t,n,a??"0x",o?je(o):"0x",c?je(c):"0x",i?je(i):"0x",s?"0x1":"0x",r??"0x"];return Ct(["0x7e",Cr(f)])}function mx(e){return e.type==="deposit"||typeof e.sourceHash<"u"}function gx(e){const{from:t,to:r}=e;if(t&&!Fe(t))throw new tt({address:t});if(r&&!Fe(r))throw new tt({address:r})}const Dn={blockTime:2e3,contracts:dx,formatters:lx,serializers:hx},bx=At({id:42161,name:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},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}}}),wx=At({id:421614,name:"Arbitrum Sepolia",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}),ci=1,vx=At({...Dn,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:{...Dn.contracts,disputeGameFactory:{[ci]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[ci]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[ci]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[ci]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:ci}),ui=11155111,Ex=At({...Dn,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:{...Dn.contracts,disputeGameFactory:{[ui]:{address:"0xd6E6dBf4F7EA0ac412fD8b65ED297e64BB7a06E1"}},l2OutputOracle:{[ui]:{address:"0x84457ca9D0163FbC4bbfe4Dfbb20ba46e48DF254"}},portal:{[ui]:{address:"0x49f53e41452c74589e85ca1677426ba426459e85",blockCreated:4446677}},l1StandardBridge:{[ui]:{address:"0xfd0Bf71F60660E2f608ed56e1659C450eB113120",blockCreated:4446677}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:1059647}},testnet:!0,sourceId:ui}),xx=At({id:80094,name:"Berachain",nativeCurrency:{decimals:18,name:"BERA Token",symbol:"BERA"},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:0},ensRegistry:{address:"0x5b22280886a2f5e09a49bea7e320eab0e5320e28",blockCreated:877007},ensUniversalResolver:{address:"0xddfb18888a9466688235887dec2a10c4f5effee9",blockCreated:877008}},rpcUrls:{default:{http:["https://rpc.berachain.com"]}},blockExplorers:{default:{name:"Berascan",url:"https://berascan.com"}},ensTlds:[".bera"],testnet:!1}),Ax=At({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}),_x=At({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}),Sx=1,Px=At({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:Sx}),Tx=At({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://eth.merkle.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensRegistry:{address:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"},ensUniversalResolver:{address:"0xce01f8eee7E479C928F8919abD53E553a36CeF67",blockCreated:19258213},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),Ix=At({id:10143,name:"Monad Testnet",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}),kx=At({id:11155111,name:"Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia.drpc.org"]}},blockExplorers:{default:{name:"Etherscan",url:"https://sepolia.etherscan.io",apiUrl:"https://api-sepolia.etherscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:751532},ensRegistry:{address:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"},ensUniversalResolver:{address:"0xc8Af999e38273D658BE1b921b88A9Ddf005769cC",blockCreated:5317080}},testnet:!0}),Cs=1,Bx=At({...Dn,id:130,name:"Unichain",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.unichain.org/"]}},blockExplorers:{default:{name:"Uniscan",url:"https://uniscan.xyz",apiUrl:"https://api.uniscan.xyz/api"}},contracts:{...Dn.contracts,multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:0},disputeGameFactory:{[Cs]:{address:"0x2F12d621a16e2d3285929C9996f478508951dFe4"}},portal:{[Cs]:{address:"0x0bd48f6B86a26D3a217d0Fa6FfE2B491B956A7a2"}},l1StandardBridge:{[Cs]:{address:"0x81014F44b0a345033bB2b3B21C7a1A308B35fEeA"}}},sourceId:Cs}),Ox={...kx,rpcUrls:{default:{http:["https://ethereum-sepolia-rpc.publicnode.com"]}}},ly={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/"]}}},py={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"]}}},hy={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"]}}},hf={ethereum:Tx,arbitrum:bx,ethereum_sepolia:Ox,arbitrum_sepolia:wx,ethereum_localnet:le.EthereumLocalnet,arbitrum_localnet:le.ArbitrumLocalnet,base_sepolia:Ex,base:vx,bera_testnet:Ax,citrea_testnet:_x,bera:xx,monad_testnet:Ix,hyperliquid_testnet:py,hyperliquid:hy,unichain:Bx,corn:Px,botanix:ly},yy=async(e,t)=>{var i,s,o;const r=hf[e],n=await t.getChainId();if(r)try{if(r.id===n)return x.Ok({message:"Already on the network",walletClient:t});await t.switchChain({id:r.id});const a=ra({account:t.account,chain:r,transport:nd(t.transport)});return x.Ok({message:"Switched chain",walletClient:a})}catch(a){if(Cx(a))if(a.code===4902)try{await t.addChain({chain:r});const c=ra({account:t.account,chain:r,transport:nd(t.transport)});return x.Ok({message:"Added network",walletClient:c})}catch{return x.Err("Failed to add network")}else if((s=(i=a.body)==null?void 0:i.method)!=null&&s.includes("wallet_switchEthereumChain")||(o=a.message)!=null&&o.includes("wallet_switchEthereumChain")){const c=ra({account:t.account,chain:r,transport:Hh()});return x.Ok({message:"Added network",walletClient:c})}else return x.Err("Failed to switch network");else return x.Err("Failed to switch network")}else return x.Err("Chain not supported")},Cx=e=>typeof e=="object"&&e!=null&&("code"in e||"message"in e||"body"in e),Rx=[{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 my{constructor(t,r,n){this.url=new x.Url("/relayer",t),this.auth=n,this.wallet=r}get htlcActorAddress(){if(!this.wallet.account)throw new Error("No account found");return this.wallet.account.address}async initiate(t){if(!this.wallet.account)return x.Err("No account found");if(this.wallet.account.address.toLowerCase()!==t.source_swap.initiator.toLowerCase())return x.Err("Account address and order initiator mismatch");if(!le.isEVM(t.source_swap.chain))return x.Err("Source chain is not an EVM chain");const r=await yy(t.source_swap.chain,this.wallet);if(!r.ok)return x.Err(r.error);if(this.wallet=r.val.walletClient,!this.wallet.account)return x.Err("No account found");const{create_order:n,source_swap:i}=t;if(!i.amount||!i.redeemer||!n.timelock||!n.secret_hash)return x.Err("Invalid order");const s=x.with0x(n.secret_hash),o=BigInt(n.timelock),a=x.with0x(i.redeemer),c=BigInt(i.amount),f=await this.getTokenAddress(t.source_swap.asset);return f.ok?le.isEvmNativeToken(t.source_swap.chain,f.val)?this._initiateOnNativeHTLC(s,o,c,a,t.source_swap.asset):this._initiateOnErc20HTLC(s,o,c,a,t.source_swap.asset,f.val,n.create_id):x.Err(f.error)}async getTokenAddress(t){try{const n=await Ko({address:x.with0x(t),abi:zd,client:this.wallet}).read.token();return x.Ok(n)}catch(r){return x.Err("Failed to get token address",String(r))}}async _initiateOnNativeHTLC(t,r,n,i,s){if(!this.wallet.account)return x.Err("No account found");try{const a=await Ko({address:x.with0x(s),abi:Rx,client:this.wallet}).write.initiate([i,r,n,t],{account:this.wallet.account,chain:this.wallet.chain,value:n});return x.Ok(a)}catch(o){return x.Err("Failed to initiate on native HTLC",String(o))}}async _initiateOnErc20HTLC(t,r,n,i,s,o,a){if(!this.wallet.account)return x.Err("No account found");try{const c=await this.auth.getAuthHeaders();if(!c.ok)return x.Err(c.error);const f=Ko({address:x.with0x(s),abi:zd,client:this.wallet}),u=await x.checkAllowanceAndApprove(Number(n),o,s,this.wallet);if(!u.ok)return x.Err(u.error);const d=await f.read.eip712Domain(),y=await this.wallet.signTypedData({account:this.wallet.account,domain:{name:d[1],version:d[2],chainId:Number(d[3]),verifyingContract:d[4]},types:{Initiate:[{name:"redeemer",type:"address"},{name:"timelock",type:"uint256"},{name:"amount",type:"uint256"},{name:"secretHash",type:"bytes32"}]},primaryType:"Initiate",message:{redeemer:i,timelock:r,amount:n,secretHash:t}}),p={...c.val,"Content-Type":"application/json"},g=await x.Fetcher.post(this.url.endpoint("initiate"),{body:JSON.stringify({order_id:a,signature:y,perform_on:"Source"}),headers:p});if(g.error)return x.Err(g.error);const b=await x.waitForTransactionReceipt(this.wallet,g.result);return b.val&&b.val.status==="success"?x.Ok(g.result?g.result:"Initiate hash not found"):x.Err("Init failed: Transaction receipt not successful")}catch(c){return console.log("init error :",c),x.Err(String(c))}}async redeem(t,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return x.Err(n.error);const i=await x.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:t.create_order.create_id,secret:x.trim0x(r),perform_on:"Destination"}),headers:{...n.val,"Content-Type":"application/json"}});if(i.error)return x.Err(i.error);const s=hf[t.destination_swap.chain],a=await Bv({chain:s,transport:Hh()}).waitForTransactionReceipt({hash:i.result,confirmations:1,timeout:3e5});return a&&a.status==="success"?x.Ok(i.result?i.result:"Redeem hash not found"):x.Err("Redeem failed: Transaction receipt not successful")}catch(n){return x.Err(String(n))}}async refund(){return x.Err("Refund not supported")}}const gy=[{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"}]}],by=async(e,t,r,n,i)=>{try{const s=await xi(e.address,t,r,i);if(!s.ok)return x.Err(s.error);if(s.val>=n)return x.Ok("Allowance already approved");const a=$e.cairo.uint256(BigInt(n)),c=await e.execute([{contractAddress:x.with0x(t),entrypoint:"approve",calldata:[x.with0x(r),a.low,a.high]}]);await i.waitForTransaction(c.transaction_hash,{retryInterval:3e3,successStates:[$e.TransactionExecutionStatus.SUCCEEDED]}),await x.sleep(2e3);for(let f=0;f<20;f++){const u=await xi(e.address,t,r,i);if(!u.ok)return x.Err(u.error);if(u.val>=n)return x.Ok(c.transaction_hash);await x.sleep(2e3);let d=0n;for(let y=0;y<20;y++){const p=await xi(e.address,t,r,i);if(!p.ok)return x.Err(p.error);if(d=p.val,d>=n)break;await x.sleep(2e3)}return d<n?x.Err("Allowance not approved"):x.Ok(c.transaction_hash)}return x.Err("Allowance not approved after transaction.")}catch(s){return x.Err(`Failed to check or approve allowance: ${s instanceof Error?s.message:String(s)}`)}},xi=async(e,t,r,n)=>{try{const s=await new $e.Contract(gy,x.with0x(t),n).call("allowance",[x.with0x(e),x.with0x(r)]);return x.Ok(BigInt((s==null?void 0:s.toString())||"0"))}catch(i){return x.Err(`Failed to check allowance: ${i instanceof Error?i.message:String(i)}`)}},wy=async(e,t,r,n,i)=>{const s=await xi(e,t,r,n);return s.ok?x.Ok(s.val>=i):x.Err(s.error)},vy=[{name:"HTLC",type:"impl",interface_name:"starknet_htlc::interface::IHTLC"},{name:"core::integer::u256",type:"struct",members:[{name:"low",type:"core::integer::u128"},{name:"high",type:"core::integer::u128"}]},{name:"starknet_htlc::interface::IHTLC",type:"interface",items:[{name:"token",type:"function",inputs:[],outputs:[{type:"core::starknet::contract_address::ContractAddress"}],state_mutability:"view"},{name:"initiate",type:"function",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::u32; 8]"}],outputs:[],state_mutability:"external"},{name:"initiate_on_behalf",type:"function",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::u32; 8]"}],outputs:[],state_mutability:"external"},{name:"initiate_with_signature",type:"function",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::u32; 8]"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"},{name:"redeem",type:"function",inputs:[{name:"order_id",type:"core::felt252"},{name:"secret",type:"core::array::Array::<core::integer::u32>"}],outputs:[],state_mutability:"external"},{name:"refund",type:"function",inputs:[{name:"order_id",type:"core::felt252"}],outputs:[],state_mutability:"external"},{name:"instant_refund",type:"function",inputs:[{name:"order_id",type:"core::felt252"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"}]},{name:"constructor",type:"constructor",inputs:[{name:"token",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"starknet_htlc::interface::events::Initiated",type:"event",members:[{kind:"key",name:"order_id",type:"core::felt252"},{kind:"data",name:"secret_hash",type:"[core::integer::u32; 8]"},{kind:"data",name:"amount",type:"core::integer::u256"}]},{kind:"struct",name:"starknet_htlc::interface::events::Redeemed",type:"event",members:[{kind:"key",name:"order_id",type:"core::felt252"},{kind:"data",name:"secret_hash",type:"[core::integer::u32; 8]"},{kind:"data",name:"secret",type:"core::array::Array::<core::integer::u32>"}]},{kind:"struct",name:"starknet_htlc::interface::events::Refunded",type:"event",members:[{kind:"key",name:"order_id",type:"core::felt252"}]},{kind:"enum",name:"starknet_htlc::htlc::HTLC::Event",type:"event",variants:[{kind:"nested",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"}]}],Nx={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*"}]};class Ey{constructor(t,r,n,i){this.url=t instanceof x.Url?t:new x.Url(t),this.account=r,this.starknetProvider=new $e.RpcProvider({nodeUrl:i||Wi[n].nodeUrl}),this.chainId=Wi[n].chainId}get htlcActorAddress(){if(!this.account.address)throw new Error("No account found");return this.account.address}async initiate(t){if(!this.account.address)return x.Err("No account address");const{create_order:r,source_swap:n}=t,{redeemer:i,amount:s}=n;if(!s||!i||!r.secret_hash||!r.timelock)return x.Err("Invalid order");try{const o=new $e.Contract(vy,t.source_swap.asset,this.account),a=await(o==null?void 0:o.token()),c=$e.num.toHex(a),f=await wy(this.account.address,c,n.asset,this.starknetProvider,BigInt(s));return f.error?x.Err(f.error):f.val?this.initiateRelay(t):this.approveAndInitiate(c,t)}catch(o){return x.Err(String(o))}}async approveAndInitiate(t,r){const{create_order:n,source_swap:i}=r,{redeemer:s,amount:o}=i,{secret_hash:a,timelock:c}=n,f=i.asset;try{const u=$e.cairo.uint256(BigInt(o)),d={contractAddress:x.with0x(t),entrypoint:"approve",calldata:[f,u.low,u.high]},y=$e.cairo.uint256(o),p={contractAddress:x.with0x(f),entrypoint:"initiate",calldata:[s,c.toString(),y.low.toString(),y.high.toString(),...x.hexToU32Array(a)]},g=await this.account.execute([d,p]);return await this.starknetProvider.waitForTransaction(g.transaction_hash,{retryInterval:2e3,successStates:[$e.TransactionExecutionStatus.SUCCEEDED]}),x.Ok(g.transaction_hash)}catch(u){return x.Err(`Failed to approve and initiate: ${String(u)}`)}}async initiateRelay(t){const{create_order:r,source_swap:n}=t,{redeemer:i,amount:s}=n,a={domain:{name:"HTLC",version:$e.shortString.encodeShortString("1"),chainId:this.chainId,revision:$e.TypedDataRevision.ACTIVE},primaryType:"Initiate",types:Nx,message:{redeemer:i,amount:$e.cairo.uint256(s),timelock:r.timelock,secretHash:x.hexToU32Array(r.secret_hash)}};try{const c=await this.account.signMessage(a),f=eE(c);if(f.error)return x.Err(f.error);const u=await x.Fetcher.post(this.url.endpoint("initiate"),{body:JSON.stringify({order_id:r.create_id,signature:f.val,perform_on:"Source"}),headers:{"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return u.error?x.Err(u.error):u.result?x.Ok(u.result):x.Err("Init: No result found")}catch(c){return x.Err(`Failed to initiate relayer: ${String(c)}`)}}async redeem(t,r){try{const n=await x.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:t.create_order.create_id,secret:r,perform_on:"Destination"}),headers:{"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return n.error?x.Err(n.error):n.result?x.Ok(n.result):x.Err("Redeem: No result found")}catch(n){return x.Err(String(n))}}async refund(){return x.Err("Refund is taken care of by the relayer")}}const Fx=e=>e.map(t=>t),$x=e=>{if(e===at.Testnet)return Ux;if(e===at.Mainnet)return Hx;throw new Error("Invalid network")},Ux=["https://mempool.space/testnet4/api"],Hx=["https://mempool.space/api","https://blockstream.info/api"],Ur={INVALID_PK:"invalid private key",FEE_EXCEEDS_AMOUNT:(e,t)=>`fee exceeds amount: fee: ${e} > amount: ${t}`,SWAP_NOT_FOUND:"swap config not found, please set the swap config first",SCRIPT_NOT_FUNDED:"script not funded",SWAP_NOT_EXPIRED:e=>`swap not expired. Need ${e} more blocks`,MIN_AMOUNT:e=>`amount is too low. Minimum amount is ${e}`,INSUFFICIENT_FUNDS:(e,t)=>`insufficient funds, need ${t} but got ${e}`,AmtPlusFeeExceedsBalance:(e,t,r)=>`amount + fee exceeds balance. Need ${e+t} but got ${r}`},yi={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"},qd=e=>e.sort((t,r)=>t.status.confirmed!=r.status.confirmed?t.status.confirmed?-1:1:r.value-t.value);class xy{constructor(t,r){this.cacheTimeout=2e3,this.utxosCache=new Map,this.APIs=r?Fx([r]):$x(t),this.network=t}async getTxIndex(t,r){const n=this.APIs.map(s=>`${s}/tx/${t}`),{vout:i}=await x.Fetcher.getWithFallback(n);for(let s=0;s<i.length;s++)if(i[s].scriptpubkey_address===r)return s;throw new Error("failed to get tx index")}async broadcast(t){if(!/^[0-9a-fA-F]+$/.test(t))throw new Error("invalid tx hex");for(let r=0;r<5;r++)try{return x.Fetcher.postWithFallback(this.APIs.map(n=>`${n}/tx`),{body:t})}catch(n){if(r===4)throw n;await new Promise(i=>setTimeout(i,500))}throw new Error("failed to broadcast tx")}async getBalance(t){return(await this.getUTXOs(t)).reduce((r,n)=>r+n.value,0)}setTimeoutForCache(t){this.cacheTimeout=t}async getUTXOs(t,r){const n=this.utxosCache.get(t);if(n&&Date.now()-n.timestamp<this.cacheTimeout)return Gd(n.utxos,r);const i=await x.Fetcher.getWithFallback(this.APIs.map(s=>`${s}/address/${t}/utxo`),{signal:AbortSignal.timeout(5e3)});return this.utxosCache.set(t,{timestamp:Date.now(),utxos:i}),Gd(i,r)}async getTransactionHex(t){return x.Fetcher.getWithFallback(this.APIs.map(r=>`${r}/tx/${t}/hex`))}async getTransaction(t){return x.Fetcher.getWithFallback(this.APIs.map(r=>`${r}/tx/${t}`))}async getConfirmations(t){const r=await this.getTransaction(t);return!r.status.confirmed||!r.status.block_height?0:await this.getLatestTip()-r.status.block_height+1}async getFeeRates(){if(this.network===at.Regtest)return{fastestFee:8,halfHourFee:7,hourFee:6,economyFee:4,minimumFee:2};let t="";this.network===at.Testnet&&(t="testnet4/");const r=`https://mempool.space/${t}api/v1/fees/recommended`,n=`https://blockstream.info/${t}api/fee-estimates`,i=await x.Fetcher.getWithFallback([r,n],{signal:AbortSignal.timeout(5e3)});return"fastestFee"in i?i.fastestFee===1?{fastestFee:2,halfHourFee:2,hourFee:2,economyFee:2,minimumFee:2}:i:{fastestFee:i[1],halfHourFee:i[5],hourFee:i[10],economyFee:i[20],minimumFee:i[25]}}async getTransactions(t,r){const n=await x.Fetcher.getWithFallback(this.APIs.map(i=>`${i}/address/${t}/txs`));if(r===Ls.ALL)return n;if(r===Ls.IN)return n.filter(i=>i.vout.find(s=>s.scriptpubkey_address===t));if(r===Ls.OUT)return n.filter(i=>i.vin.find(s=>s.prevout.scriptpubkey_address===t));throw new Error("failed to get transactions: invalid bitcoin tx type")}getNetwork(){return this.network}async getLatestTip(){return x.Fetcher.getWithFallback(this.APIs.map(t=>`${t}/blocks/tip/height`))}async suggestFee(t,r,n){const s=(await this.getUTXOs(t,r)).length,o=2,a=await this.getFeeRates();return Math.floor(a[Vv[n]]*1.05)*(s*70+o*31+10)}async getTransactionTimes(t){const r=t.map(i=>`txId[]=${i}`).join("&");return(await x.Fetcher.getWithFallback(this.APIs.map(i=>`${i}/v1/transaction-times?${r}`))).map(i=>i*1e3)}}const Gd=(e,t)=>{if(Array.isArray(e)){if(t){const r=e.reduce((s,o)=>s+o.value,0);if(r<t)throw new Error(Ur.INSUFFICIENT_FUNDS(r,t));let n=BigInt(0);e.sort((s,o)=>o.value-s.value);const i=[];for(const s of e)if(n+=BigInt(s.value),i.push(s),n>=t)break;return qd(i)}return qd(e)}return[]},fi={p2wpkh:"p2wpkh","p2wpkh-p2sh":"p2wpkh-p2sh"},qs={ALL:oe.Transaction.SIGHASH_ALL,NONE:oe.Transaction.SIGHASH_NONE,SINGLE:oe.Transaction.SIGHASH_SINGLE,ALL_ANYONECANPAY:oe.Transaction.SIGHASH_ALL|oe.Transaction.SIGHASH_ANYONECANPAY,NONE_ANYONECANPAY:oe.Transaction.SIGHASH_NONE|oe.Transaction.SIGHASH_ANYONECANPAY,SINGLE_ANYONECANPAY:oe.Transaction.SIGHASH_SINGLE|oe.Transaction.SIGHASH_ANYONECANPAY};class Wr{constructor(t,r){this._scriptType=t,this._sigHashType=r}get scriptType(){return this._scriptType}get sigHashType(){return this._sigHashType}toString(){return`${this._scriptType} ${this._sigHashType}`}static async fromString(t){const[r,n]=t.split(" "),i=await vf.mixed().oneOf(["segwitV0","segwitV1","p2shSignature"]).required().validate(r),s=await vf.mixed().oneOf(Object.values(qs)).required().validate(parseInt(n));return new Wr(i,s)}}const Lx=(e,t,r=!1)=>{const n=o=>{try{o=oe.address.fromBech32(o).data.toString("hex")}catch(a){if(ru(a))(a.message.includes("Mixed-case string")||a.message.includes("too short"))&&(o=oe.address.fromBase58Check(o).hash.toString("hex"));else throw new Error(String(a))}return o},i=oe.script.fromASM(`
72
+ `.trim().replace(/\s+/g," "))}leaves(){return[{version:Os,output:this.redeemLeaf()},[{version:Os,output:this.refundLeaf()},{version:Os,output:this.instantRefundLeaf()}]]}generateMerkleProofFor(t){const r=this.leafHash(1),n=this.leafHash(2),i=this.leafHash(0);switch(t){case 1:{const s=Yv(i,n);return[pe.crypto.taggedHash("TapBranch",Buffer.concat(s))]}case 0:return[n,r];case 2:return[i,r];default:throw new Error(Ze.invalidLeaf)}}}function ai(e,t){const r=[];for(let n=0;n<t;n++)r.push(e);return r}class ux{constructor(){this.cache={}}set(t,r,n,i){const s={txHash:n,timeStamp:Date.now(),btcRedeemUTXO:i};this.cache[`${r}_${t.create_order.create_id}`]=s}get(t,r){return this.cache[`${r}_${t.create_order.create_id}`]||null}remove(t,r){delete this.cache[`${r}_${t.create_order.create_id}`]}}class fx{constructor(){this.cache={}}set(t,r){this.cache[t]=r}get(t){return this.cache[t]||null}}class fy{constructor(t,r){this.url=new x.Url(t).endpoint("blocknumbers").endpoint(r)}async fetchBlockNumbers(){try{const t=await x.Fetcher.get(this.url);return x.Ok(t)}catch(t){return x.Err("Failed to fetch block numbers",t)}}}class dy{constructor(t){this.quoteUrl=new x.Url(t)}async getQuoteFromAssets({fromAsset:t,toAsset:r,amount:n,isExactOut:i=!1,options:s}){const o=eu(t.chain,t.atomicSwapAddress,r.chain,r.atomicSwapAddress);return this.getQuote(o,n,i,s)}async getQuote(t,r,n=!1,i){try{const s={order_pair:t,amount:r.toString(),exact_out:n.toString(),...(i==null?void 0:i.affiliateFee)!==void 0&&{affiliate_fee:i.affiliateFee.toString()}},o=this.quoteUrl.endpoint("/").addSearchParams(s),a=await x.Fetcher.get(o,{retryCount:0,...i==null?void 0:i.request});return a.error?x.Err(a.error):a.result?x.Ok(a.result):x.Err("GetQuote: Unexpected error, result is undefined")}catch(s){return x.Err("GetQuote:",String(s))}}async getAttestedQuote(t){try{const r=await x.Fetcher.post(this.quoteUrl.endpoint("/attested").toString(),{body:JSON.stringify(t),headers:{"Content-Type":"application/json"}});return r.error?x.Err(r.error):r.result?x.Ok(r.result):x.Err("GetAttestedQuote: Unexpected error, result is undefined")}catch(r){return console.log("error :",r),x.Err("GetAttestedQuote:",String(r))}}async getStrategies(){try{const t=await x.Fetcher.get(this.quoteUrl.endpoint("/strategies"));if(t.error)return x.Err(t.error);if(!t.result)return x.Err("GetStrategies: Unexpected error, result is undefined");const r={};for(const n of Object.values(t.result)){const i=eu(n.source_chain,n.source_asset.asset,n.dest_chain,n.dest_asset.asset);r[i]={id:n.id,minAmount:n.min_amount,maxAmount:n.max_amount,fee:n.fee,fixed_fee:Number(n.fixed_fee)}}return x.Ok(r)}catch(t){return x.Err("GetStrategies:",String(t))}}}class Xi extends x.EventBroker{get isInitialized(){return!!this.digestKey}constructor(t,r){super(),this.digestKey=t,this.walletClient=r}static fromDigestKey(t){return new Xi(x.trim0x(t))}static fromWalletClient(t){return new Xi(void 0,t)}async initialize(){if(this.digestKey)return x.Ok("Already initialized");const t=await this.deriveDigestKeyFromWalletClient();return t.error?x.Err(t.error):(this.emit("initialized",!0),x.Ok("Initialized"))}async deriveDigestKeyFromWalletClient(){if(!this.walletClient)return x.Err("No walletClient found");if(!this.walletClient.account)return x.Err("No account found");try{const t=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=x.trim0x(di(t)),this.emit("initialized",!0),x.Ok(this.digestKey)}catch(t){return x.Err("Failed to initialize: "+t)}}async getDigestKey(){if(!this.digestKey&&!this.walletClient)return x.Err("No private key or wallet client found");if(!this.digestKey&&this.walletClient){const t=await this.deriveDigestKeyFromWalletClient();if(t.error)return x.Err(t.error)}return this.digestKey?x.Ok(this.digestKey):x.Err("No private key found")}async generateSecret(t){const r=await this.signMessage(t);if(!r.ok)return x.Err(r.error);const n=di(x.with0x(r.val)),i=di(n);return x.Ok({secret:n,secretHash:i})}async signMessage(t){if(!this.digestKey){const f=await this.getDigestKey();if(!f.ok)return x.Err(f.error);this.digestKey=f.val}const r=Fs.ECPairFactory(wt),n="Garden.fi"+t.toString(),i=Buffer.from(n,"utf8"),s=di(i),o=Buffer.from(x.trim0x(this.digestKey),"hex");if(o.length!==32)return x.Err("Invalid private key length. Expected 32 bytes.");const c=r.fromPrivateKey(o).sign(Buffer.from(x.trim0x(s),"hex"));return x.Ok(c.toString("hex"))}}const zd=[{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"}],dx={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}},lx={block:kb({format(e){var r;return{transactions:(r=e.transactions)==null?void 0:r.map(n=>{if(typeof n=="string")return n;const i=fo(n);return i.typeHex==="0x7e"&&(i.isSystemTx=n.isSystemTx,i.mint=n.mint?Ue(n.mint):void 0,i.sourceHash=n.sourceHash,i.type="deposit"),i}),stateRoot:e.stateRoot}}}),transaction:Tb({format(e){const t={};return e.type==="0x7e"&&(t.isSystemTx=e.isSystemTx,t.mint=e.mint?Ue(e.mint):void 0,t.sourceHash=e.sourceHash,t.type="deposit"),t}}),transactionReceipt:Hw({format(e){return{l1GasPrice:e.l1GasPrice?Ue(e.l1GasPrice):null,l1GasUsed:e.l1GasUsed?Ue(e.l1GasUsed):null,l1Fee:e.l1Fee?Ue(e.l1Fee):null,l1FeeScalar:e.l1FeeScalar?Number(e.l1FeeScalar):null}}})};function px(e,t){return mx(e)?yx(e):H1(e,t)}const hx={transaction:px};function yx(e){gx(e);const{sourceHash:t,data:r,from:n,gas:i,isSystemTx:s,mint:o,to:a,value:c}=e,f=[t,n,a??"0x",o?je(o):"0x",c?je(c):"0x",i?je(i):"0x",s?"0x1":"0x",r??"0x"];return Ct(["0x7e",Cr(f)])}function mx(e){return e.type==="deposit"||typeof e.sourceHash<"u"}function gx(e){const{from:t,to:r}=e;if(t&&!Fe(t))throw new tt({address:t});if(r&&!Fe(r))throw new tt({address:r})}const Dn={blockTime:2e3,contracts:dx,formatters:lx,serializers:hx},bx=ot({id:42161,name:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},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}}}),wx=ot({id:421614,name:"Arbitrum Sepolia",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}),ci=1,vx=ot({...Dn,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:{...Dn.contracts,disputeGameFactory:{[ci]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[ci]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[ci]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[ci]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:ci}),ui=11155111,Ex=ot({...Dn,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:{...Dn.contracts,disputeGameFactory:{[ui]:{address:"0xd6E6dBf4F7EA0ac412fD8b65ED297e64BB7a06E1"}},l2OutputOracle:{[ui]:{address:"0x84457ca9D0163FbC4bbfe4Dfbb20ba46e48DF254"}},portal:{[ui]:{address:"0x49f53e41452c74589e85ca1677426ba426459e85",blockCreated:4446677}},l1StandardBridge:{[ui]:{address:"0xfd0Bf71F60660E2f608ed56e1659C450eB113120",blockCreated:4446677}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:1059647}},testnet:!0,sourceId:ui}),xx=ot({id:80094,name:"Berachain",nativeCurrency:{decimals:18,name:"BERA Token",symbol:"BERA"},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:0},ensRegistry:{address:"0x5b22280886a2f5e09a49bea7e320eab0e5320e28",blockCreated:877007},ensUniversalResolver:{address:"0xddfb18888a9466688235887dec2a10c4f5effee9",blockCreated:877008}},rpcUrls:{default:{http:["https://rpc.berachain.com"]}},blockExplorers:{default:{name:"Berascan",url:"https://berascan.com"}},ensTlds:[".bera"],testnet:!1}),Ax=ot({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}),_x=ot({id:56,name:"BNB Smart Chain",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}}}),Sx=ot({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}),Px=ot({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}),Tx=1,Ix=ot({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:Tx}),kx=ot({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://eth.merkle.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensRegistry:{address:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"},ensUniversalResolver:{address:"0xce01f8eee7E479C928F8919abD53E553a36CeF67",blockCreated:19258213},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),Bx=ot({id:10143,name:"Monad Testnet",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}),Ox=ot({id:11155111,name:"Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia.drpc.org"]}},blockExplorers:{default:{name:"Etherscan",url:"https://sepolia.etherscan.io",apiUrl:"https://api-sepolia.etherscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:751532},ensRegistry:{address:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"},ensUniversalResolver:{address:"0xc8Af999e38273D658BE1b921b88A9Ddf005769cC",blockCreated:5317080}},testnet:!0}),Cs=1,Cx=ot({...Dn,id:130,name:"Unichain",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.unichain.org/"]}},blockExplorers:{default:{name:"Uniscan",url:"https://uniscan.xyz",apiUrl:"https://api.uniscan.xyz/api"}},contracts:{...Dn.contracts,multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:0},disputeGameFactory:{[Cs]:{address:"0x2F12d621a16e2d3285929C9996f478508951dFe4"}},portal:{[Cs]:{address:"0x0bd48f6B86a26D3a217d0Fa6FfE2B491B956A7a2"}},l1StandardBridge:{[Cs]:{address:"0x81014F44b0a345033bB2b3B21C7a1A308B35fEeA"}}},sourceId:Cs}),Rx={...Ox,rpcUrls:{default:{http:["https://ethereum-sepolia-rpc.publicnode.com"]}}},ly={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/"]}}},py={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"]}}},hy={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"]}}},hf={ethereum:kx,arbitrum:bx,ethereum_sepolia:Rx,arbitrum_sepolia:wx,ethereum_localnet:le.EthereumLocalnet,arbitrum_localnet:le.ArbitrumLocalnet,base_sepolia:Ex,base:vx,bera_testnet:Ax,citrea_testnet:Px,bera:xx,monad_testnet:Bx,hyperliquid_testnet:py,hyperliquid:hy,unichain:Cx,corn:Ix,botanix:ly,bnbchain:_x,bnbchain_testnet:Sx},yy=async(e,t)=>{var i,s,o;const r=hf[e],n=await t.getChainId();if(r)try{if(r.id===n)return x.Ok({message:"Already on the network",walletClient:t});await t.switchChain({id:r.id});const a=ra({account:t.account,chain:r,transport:nd(t.transport)});return x.Ok({message:"Switched chain",walletClient:a})}catch(a){if(Nx(a))if(a.code===4902)try{await t.addChain({chain:r});const c=ra({account:t.account,chain:r,transport:nd(t.transport)});return x.Ok({message:"Added network",walletClient:c})}catch{return x.Err("Failed to add network")}else if((s=(i=a.body)==null?void 0:i.method)!=null&&s.includes("wallet_switchEthereumChain")||(o=a.message)!=null&&o.includes("wallet_switchEthereumChain")){const c=ra({account:t.account,chain:r,transport:Hh()});return x.Ok({message:"Added network",walletClient:c})}else return x.Err("Failed to switch network");else return x.Err("Failed to switch network")}else return x.Err("Chain not supported")},Nx=e=>typeof e=="object"&&e!=null&&("code"in e||"message"in e||"body"in e),Fx=[{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 my{constructor(t,r,n){this.url=new x.Url("/relayer",t),this.auth=n,this.wallet=r}get htlcActorAddress(){if(!this.wallet.account)throw new Error("No account found");return this.wallet.account.address}async initiate(t){if(!this.wallet.account)return x.Err("No account found");if(this.wallet.account.address.toLowerCase()!==t.source_swap.initiator.toLowerCase())return x.Err("Account address and order initiator mismatch");if(!le.isEVM(t.source_swap.chain))return x.Err("Source chain is not an EVM chain");const r=await yy(t.source_swap.chain,this.wallet);if(!r.ok)return x.Err(r.error);if(this.wallet=r.val.walletClient,!this.wallet.account)return x.Err("No account found");const{create_order:n,source_swap:i}=t;if(!i.amount||!i.redeemer||!n.timelock||!n.secret_hash)return x.Err("Invalid order");const s=x.with0x(n.secret_hash),o=BigInt(n.timelock),a=x.with0x(i.redeemer),c=BigInt(i.amount),f=await this.getTokenAddress(t.source_swap.asset);return f.ok?le.isEvmNativeToken(t.source_swap.chain,f.val)?this._initiateOnNativeHTLC(s,o,c,a,t.source_swap.asset):this._initiateOnErc20HTLC(s,o,c,a,t.source_swap.asset,f.val,n.create_id):x.Err(f.error)}async getTokenAddress(t){try{const n=await Ko({address:x.with0x(t),abi:zd,client:this.wallet}).read.token();return x.Ok(n)}catch(r){return x.Err("Failed to get token address",String(r))}}async _initiateOnNativeHTLC(t,r,n,i,s){if(!this.wallet.account)return x.Err("No account found");try{const a=await Ko({address:x.with0x(s),abi:Fx,client:this.wallet}).write.initiate([i,r,n,t],{account:this.wallet.account,chain:this.wallet.chain,value:n});return x.Ok(a)}catch(o){return x.Err("Failed to initiate on native HTLC",String(o))}}async _initiateOnErc20HTLC(t,r,n,i,s,o,a){if(!this.wallet.account)return x.Err("No account found");try{const c=await this.auth.getAuthHeaders();if(!c.ok)return x.Err(c.error);const f=Ko({address:x.with0x(s),abi:zd,client:this.wallet}),u=await x.checkAllowanceAndApprove(Number(n),o,s,this.wallet);if(!u.ok)return x.Err(u.error);const d=await f.read.eip712Domain(),y=await this.wallet.signTypedData({account:this.wallet.account,domain:{name:d[1],version:d[2],chainId:Number(d[3]),verifyingContract:d[4]},types:{Initiate:[{name:"redeemer",type:"address"},{name:"timelock",type:"uint256"},{name:"amount",type:"uint256"},{name:"secretHash",type:"bytes32"}]},primaryType:"Initiate",message:{redeemer:i,timelock:r,amount:n,secretHash:t}}),p={...c.val,"Content-Type":"application/json"},g=await x.Fetcher.post(this.url.endpoint("initiate"),{body:JSON.stringify({order_id:a,signature:y,perform_on:"Source"}),headers:p});if(g.error)return x.Err(g.error);const b=await x.waitForTransactionReceipt(this.wallet,g.result);return b.val&&b.val.status==="success"?x.Ok(g.result?g.result:"Initiate hash not found"):x.Err("Init failed: Transaction receipt not successful")}catch(c){return console.log("init error :",c),x.Err(String(c))}}async redeem(t,r){try{const n=await this.auth.getAuthHeaders();if(!n.ok)return x.Err(n.error);const i=await x.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:t.create_order.create_id,secret:x.trim0x(r),perform_on:"Destination"}),headers:{...n.val,"Content-Type":"application/json"}});if(i.error)return x.Err(i.error);const s=hf[t.destination_swap.chain],a=await Bv({chain:s,transport:Hh()}).waitForTransactionReceipt({hash:i.result,confirmations:1,timeout:3e5});return a&&a.status==="success"?x.Ok(i.result?i.result:"Redeem hash not found"):x.Err("Redeem failed: Transaction receipt not successful")}catch(n){return x.Err(String(n))}}async refund(){return x.Err("Refund not supported")}}const gy=[{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"}]}],by=async(e,t,r,n,i)=>{try{const s=await xi(e.address,t,r,i);if(!s.ok)return x.Err(s.error);if(s.val>=n)return x.Ok("Allowance already approved");const a=$e.cairo.uint256(BigInt(n)),c=await e.execute([{contractAddress:x.with0x(t),entrypoint:"approve",calldata:[x.with0x(r),a.low,a.high]}]);await i.waitForTransaction(c.transaction_hash,{retryInterval:3e3,successStates:[$e.TransactionExecutionStatus.SUCCEEDED]}),await x.sleep(2e3);for(let f=0;f<20;f++){const u=await xi(e.address,t,r,i);if(!u.ok)return x.Err(u.error);if(u.val>=n)return x.Ok(c.transaction_hash);await x.sleep(2e3);let d=0n;for(let y=0;y<20;y++){const p=await xi(e.address,t,r,i);if(!p.ok)return x.Err(p.error);if(d=p.val,d>=n)break;await x.sleep(2e3)}return d<n?x.Err("Allowance not approved"):x.Ok(c.transaction_hash)}return x.Err("Allowance not approved after transaction.")}catch(s){return x.Err(`Failed to check or approve allowance: ${s instanceof Error?s.message:String(s)}`)}},xi=async(e,t,r,n)=>{try{const s=await new $e.Contract(gy,x.with0x(t),n).call("allowance",[x.with0x(e),x.with0x(r)]);return x.Ok(BigInt((s==null?void 0:s.toString())||"0"))}catch(i){return x.Err(`Failed to check allowance: ${i instanceof Error?i.message:String(i)}`)}},wy=async(e,t,r,n,i)=>{const s=await xi(e,t,r,n);return s.ok?x.Ok(s.val>=i):x.Err(s.error)},vy=[{name:"HTLC",type:"impl",interface_name:"starknet_htlc::interface::IHTLC"},{name:"core::integer::u256",type:"struct",members:[{name:"low",type:"core::integer::u128"},{name:"high",type:"core::integer::u128"}]},{name:"starknet_htlc::interface::IHTLC",type:"interface",items:[{name:"token",type:"function",inputs:[],outputs:[{type:"core::starknet::contract_address::ContractAddress"}],state_mutability:"view"},{name:"initiate",type:"function",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::u32; 8]"}],outputs:[],state_mutability:"external"},{name:"initiate_on_behalf",type:"function",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::u32; 8]"}],outputs:[],state_mutability:"external"},{name:"initiate_with_signature",type:"function",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::u32; 8]"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"},{name:"redeem",type:"function",inputs:[{name:"order_id",type:"core::felt252"},{name:"secret",type:"core::array::Array::<core::integer::u32>"}],outputs:[],state_mutability:"external"},{name:"refund",type:"function",inputs:[{name:"order_id",type:"core::felt252"}],outputs:[],state_mutability:"external"},{name:"instant_refund",type:"function",inputs:[{name:"order_id",type:"core::felt252"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"}]},{name:"constructor",type:"constructor",inputs:[{name:"token",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"starknet_htlc::interface::events::Initiated",type:"event",members:[{kind:"key",name:"order_id",type:"core::felt252"},{kind:"data",name:"secret_hash",type:"[core::integer::u32; 8]"},{kind:"data",name:"amount",type:"core::integer::u256"}]},{kind:"struct",name:"starknet_htlc::interface::events::Redeemed",type:"event",members:[{kind:"key",name:"order_id",type:"core::felt252"},{kind:"data",name:"secret_hash",type:"[core::integer::u32; 8]"},{kind:"data",name:"secret",type:"core::array::Array::<core::integer::u32>"}]},{kind:"struct",name:"starknet_htlc::interface::events::Refunded",type:"event",members:[{kind:"key",name:"order_id",type:"core::felt252"}]},{kind:"enum",name:"starknet_htlc::htlc::HTLC::Event",type:"event",variants:[{kind:"nested",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"}]}],$x={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*"}]};class Ey{constructor(t,r,n,i){this.url=t instanceof x.Url?t:new x.Url(t),this.account=r,this.starknetProvider=new $e.RpcProvider({nodeUrl:i||Wi[n].nodeUrl}),this.chainId=Wi[n].chainId}get htlcActorAddress(){if(!this.account.address)throw new Error("No account found");return this.account.address}async initiate(t){if(!this.account.address)return x.Err("No account address");const{create_order:r,source_swap:n}=t,{redeemer:i,amount:s}=n;if(!s||!i||!r.secret_hash||!r.timelock)return x.Err("Invalid order");try{const o=new $e.Contract(vy,t.source_swap.asset,this.account),a=await(o==null?void 0:o.token()),c=$e.num.toHex(a),f=await wy(this.account.address,c,n.asset,this.starknetProvider,BigInt(s));return f.error?x.Err(f.error):f.val?this.initiateRelay(t):this.approveAndInitiate(c,t)}catch(o){return x.Err(String(o))}}async approveAndInitiate(t,r){const{create_order:n,source_swap:i}=r,{redeemer:s,amount:o}=i,{secret_hash:a,timelock:c}=n,f=i.asset;try{const u=$e.cairo.uint256(BigInt(o)),d={contractAddress:x.with0x(t),entrypoint:"approve",calldata:[f,u.low,u.high]},y=$e.cairo.uint256(o),p={contractAddress:x.with0x(f),entrypoint:"initiate",calldata:[s,c.toString(),y.low.toString(),y.high.toString(),...x.hexToU32Array(a)]},g=await this.account.execute([d,p]);return await this.starknetProvider.waitForTransaction(g.transaction_hash,{retryInterval:2e3,successStates:[$e.TransactionExecutionStatus.SUCCEEDED]}),x.Ok(g.transaction_hash)}catch(u){return x.Err(`Failed to approve and initiate: ${String(u)}`)}}async initiateRelay(t){const{create_order:r,source_swap:n}=t,{redeemer:i,amount:s}=n,a={domain:{name:"HTLC",version:$e.shortString.encodeShortString("1"),chainId:this.chainId,revision:$e.TypedDataRevision.ACTIVE},primaryType:"Initiate",types:$x,message:{redeemer:i,amount:$e.cairo.uint256(s),timelock:r.timelock,secretHash:x.hexToU32Array(r.secret_hash)}};try{const c=await this.account.signMessage(a),f=eE(c);if(f.error)return x.Err(f.error);const u=await x.Fetcher.post(this.url.endpoint("initiate"),{body:JSON.stringify({order_id:r.create_id,signature:f.val,perform_on:"Source"}),headers:{"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return u.error?x.Err(u.error):u.result?x.Ok(u.result):x.Err("Init: No result found")}catch(c){return x.Err(`Failed to initiate relayer: ${String(c)}`)}}async redeem(t,r){try{const n=await x.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:t.create_order.create_id,secret:r,perform_on:"Destination"}),headers:{"Content-Type":"application/json"},retryCount:10,retryDelay:2e3});return n.error?x.Err(n.error):n.result?x.Ok(n.result):x.Err("Redeem: No result found")}catch(n){return x.Err(String(n))}}async refund(){return x.Err("Refund is taken care of by the relayer")}}const Ux=e=>e.map(t=>t),Hx=e=>{if(e===ct.Testnet)return Lx;if(e===ct.Mainnet)return Mx;throw new Error("Invalid network")},Lx=["https://mempool.space/testnet4/api"],Mx=["https://mempool.space/api","https://blockstream.info/api"],Ur={INVALID_PK:"invalid private key",FEE_EXCEEDS_AMOUNT:(e,t)=>`fee exceeds amount: fee: ${e} > amount: ${t}`,SWAP_NOT_FOUND:"swap config not found, please set the swap config first",SCRIPT_NOT_FUNDED:"script not funded",SWAP_NOT_EXPIRED:e=>`swap not expired. Need ${e} more blocks`,MIN_AMOUNT:e=>`amount is too low. Minimum amount is ${e}`,INSUFFICIENT_FUNDS:(e,t)=>`insufficient funds, need ${t} but got ${e}`,AmtPlusFeeExceedsBalance:(e,t,r)=>`amount + fee exceeds balance. Need ${e+t} but got ${r}`},yi={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"},qd=e=>e.sort((t,r)=>t.status.confirmed!=r.status.confirmed?t.status.confirmed?-1:1:r.value-t.value);class xy{constructor(t,r){this.cacheTimeout=2e3,this.utxosCache=new Map,this.APIs=r?Ux([r]):Hx(t),this.network=t}async getTxIndex(t,r){const n=this.APIs.map(s=>`${s}/tx/${t}`),{vout:i}=await x.Fetcher.getWithFallback(n);for(let s=0;s<i.length;s++)if(i[s].scriptpubkey_address===r)return s;throw new Error("failed to get tx index")}async broadcast(t){if(!/^[0-9a-fA-F]+$/.test(t))throw new Error("invalid tx hex");for(let r=0;r<5;r++)try{return x.Fetcher.postWithFallback(this.APIs.map(n=>`${n}/tx`),{body:t})}catch(n){if(r===4)throw n;await new Promise(i=>setTimeout(i,500))}throw new Error("failed to broadcast tx")}async getBalance(t){return(await this.getUTXOs(t)).reduce((r,n)=>r+n.value,0)}setTimeoutForCache(t){this.cacheTimeout=t}async getUTXOs(t,r){const n=this.utxosCache.get(t);if(n&&Date.now()-n.timestamp<this.cacheTimeout)return Gd(n.utxos,r);const i=await x.Fetcher.getWithFallback(this.APIs.map(s=>`${s}/address/${t}/utxo`),{signal:AbortSignal.timeout(5e3)});return this.utxosCache.set(t,{timestamp:Date.now(),utxos:i}),Gd(i,r)}async getTransactionHex(t){return x.Fetcher.getWithFallback(this.APIs.map(r=>`${r}/tx/${t}/hex`))}async getTransaction(t){return x.Fetcher.getWithFallback(this.APIs.map(r=>`${r}/tx/${t}`))}async getConfirmations(t){const r=await this.getTransaction(t);return!r.status.confirmed||!r.status.block_height?0:await this.getLatestTip()-r.status.block_height+1}async getFeeRates(){if(this.network===ct.Regtest)return{fastestFee:8,halfHourFee:7,hourFee:6,economyFee:4,minimumFee:2};let t="";this.network===ct.Testnet&&(t="testnet4/");const r=`https://mempool.space/${t}api/v1/fees/recommended`,n=`https://blockstream.info/${t}api/fee-estimates`,i=await x.Fetcher.getWithFallback([r,n],{signal:AbortSignal.timeout(5e3)});return"fastestFee"in i?i.fastestFee===1?{fastestFee:2,halfHourFee:2,hourFee:2,economyFee:2,minimumFee:2}:i:{fastestFee:i[1],halfHourFee:i[5],hourFee:i[10],economyFee:i[20],minimumFee:i[25]}}async getTransactions(t,r){const n=await x.Fetcher.getWithFallback(this.APIs.map(i=>`${i}/address/${t}/txs`));if(r===Ls.ALL)return n;if(r===Ls.IN)return n.filter(i=>i.vout.find(s=>s.scriptpubkey_address===t));if(r===Ls.OUT)return n.filter(i=>i.vin.find(s=>s.prevout.scriptpubkey_address===t));throw new Error("failed to get transactions: invalid bitcoin tx type")}getNetwork(){return this.network}async getLatestTip(){return x.Fetcher.getWithFallback(this.APIs.map(t=>`${t}/blocks/tip/height`))}async suggestFee(t,r,n){const s=(await this.getUTXOs(t,r)).length,o=2,a=await this.getFeeRates();return Math.floor(a[Vv[n]]*1.05)*(s*70+o*31+10)}async getTransactionTimes(t){const r=t.map(i=>`txId[]=${i}`).join("&");return(await x.Fetcher.getWithFallback(this.APIs.map(i=>`${i}/v1/transaction-times?${r}`))).map(i=>i*1e3)}}const Gd=(e,t)=>{if(Array.isArray(e)){if(t){const r=e.reduce((s,o)=>s+o.value,0);if(r<t)throw new Error(Ur.INSUFFICIENT_FUNDS(r,t));let n=BigInt(0);e.sort((s,o)=>o.value-s.value);const i=[];for(const s of e)if(n+=BigInt(s.value),i.push(s),n>=t)break;return qd(i)}return qd(e)}return[]},fi={p2wpkh:"p2wpkh","p2wpkh-p2sh":"p2wpkh-p2sh"},qs={ALL:oe.Transaction.SIGHASH_ALL,NONE:oe.Transaction.SIGHASH_NONE,SINGLE:oe.Transaction.SIGHASH_SINGLE,ALL_ANYONECANPAY:oe.Transaction.SIGHASH_ALL|oe.Transaction.SIGHASH_ANYONECANPAY,NONE_ANYONECANPAY:oe.Transaction.SIGHASH_NONE|oe.Transaction.SIGHASH_ANYONECANPAY,SINGLE_ANYONECANPAY:oe.Transaction.SIGHASH_SINGLE|oe.Transaction.SIGHASH_ANYONECANPAY};class Wr{constructor(t,r){this._scriptType=t,this._sigHashType=r}get scriptType(){return this._scriptType}get sigHashType(){return this._sigHashType}toString(){return`${this._scriptType} ${this._sigHashType}`}static async fromString(t){const[r,n]=t.split(" "),i=await vf.mixed().oneOf(["segwitV0","segwitV1","p2shSignature"]).required().validate(r),s=await vf.mixed().oneOf(Object.values(qs)).required().validate(parseInt(n));return new Wr(i,s)}}const Dx=(e,t,r=!1)=>{const n=o=>{try{o=oe.address.fromBech32(o).data.toString("hex")}catch(a){if(ru(a))(a.message.includes("Mixed-case string")||a.message.includes("too short"))&&(o=oe.address.fromBase58Check(o).hash.toString("hex"));else throw new Error(String(a))}return o},i=oe.script.fromASM(`
73
73
  OP_IF
74
74
  OP_SHA256
75
75
  ${e.secretHash}
@@ -87,7 +87,7 @@ ${tb(p)}`),super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessa
87
87
  OP_ENDIF
88
88
  OP_EQUALVERIFY
89
89
  OP_CHECKSIG
90
- `.trim().replace(/\s+/g," ")),s=oe.payments[r?"p2sh":"p2wsh"]({redeem:{output:i},network:t});if(!s.address)throw new Error("Could not build address");return{script:i,address:s.address}},Ai={P2SH:"p2sh",P2WSH:"p2wsh",P2TR:"p2tr"};var Ay=(e=>(e[e.Bitcoin=0]="Bitcoin",e[e.EVM=1]="EVM",e))(Ay||{});class Mx{addSignatureSegwitV0(t=qs.ALL){return new Wr("segwitV0",t)}addSignatureP2sh(t=qs.ALL){return new Wr("p2shSignature",t)}addSignatureSegwitV1(t=qs.ALL){return new Wr("segwitV1",t)}chain(){return Ay.Bitcoin}async addAllInputs(t,r,n,i){const s=(i==null?void 0:i.utxos)||await n.getUTXOs(r);for(const o of s){const a=await n.getTxIndex(o.txid,r);t.addInput(tu(o.txid),a,i==null?void 0:i.nSequence)}return t}async suggestFee(t,r){const n=await this.getAddress();return(await this.getProvider()).suggestFee(n,t,r)}async toOutputScript(t){return oe.address.toOutputScript(t,await this.getNetwork())}totalValueFromUTXOs(t){return t.reduce((r,n)=>r+n.value,0)}async scriptToAddress(t){const r=oe.payments.p2wsh({redeem:{output:t},network:await this.getNetwork()});if(!r.address)throw new Error("Could not generate p2wsh address");return r.address}async newSwap(t){if(t.secretHash=x.trim0x(t.secretHash),t.secretHash.length!==64)throw new Error(yi.INVALID_SECRET_HASH);const{script:r,address:n}=Lx(t,await this.getNetwork());return new Dx(this,{...t,redeemScript:r,scriptAddress:n})}getScriptType(t,r){try{if(oe.address.fromBase58Check(t).version===r.scriptHash)return Ai.P2SH}catch{const i=oe.address.fromBech32(t);if(i.prefix!==r.bech32)throw new Error("Invalid address");if(i.version===0){if(i.data.length===32)return Ai.P2WSH}else if(i.version===1&&i.data.length===32)return Ai.P2TR}throw new Error("Unsupported script type")}}class Dx{constructor(t,r){if(r.secretHash=x.trim0x(r.secretHash),r.secretHash.length!==64)throw new Error(yi.INVALID_SECRET_HASH);this.wallet=t,this.swap=r}id(){return this.swap.scriptAddress}async init(){return this.wallet.send(this.swap.scriptAddress,+this.swap.amount.toString())}async redeem(t,r){t=x.trim0x(t);const n=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),Buffer.from(t,"hex"),oe.script.number.encode(1),this.swap.redeemScript],i=oe.payments.p2wsh({redeem:{output:this.swap.redeemScript},network:await this.wallet.getNetwork()}).address;if(!i)throw new Error("Could not generate p2wsh address for redeem script");try{return await this.wallet.spend(this.swap.redeemScript,i,{witness:n,toAddress:r})}catch(s){throw ru(s)?s.message.includes("OP_EQUALVERIFY")?new Error(yi.INVALID_PUBKEY_OR_SECRET):new Error(s.message):new Error(String(s))}}async refund(t){const r=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),oe.script.number.encode(0),this.swap.redeemScript];try{const n=oe.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:t,witness:r,nSequence:this.swap.expiryBlocks})}catch(n){throw ru(n)?n.message.includes("OP_EQUALVERIFY")?new Error(yi.INVALID_PUBKEY):n.message.includes("BIP")?new Error(yi.ORDER_NOT_EXPIRED):new Error(n.message):new Error(String(n))}}}const ya=(e,t,r,n)=>`m/${e}'/${t===at.Mainnet?0:1}'/${r}'/0/${n??0}`,_y={bip44:(e,t,r)=>ya("44",e,r??0,t),bip49:(e,t,r)=>ya("49",e,r??0,t),bip84:(e,t,r)=>ya("84",e,r??0,t)};function ma(e){if(e===at.Mainnet)return oe.networks.bitcoin;if(e===at.Testnet)return oe.networks.testnet;if(e===at.Regtest)return oe.networks.regtest;throw new Error("Invalid network")}function jx(e,t,r){if(!Ef.validateMnemonic(e))throw new Error("Invalid mnemonic");const n=(r==null?void 0:r.path)??_y.bip44(t,(r==null?void 0:r.index)??0),i=jy.BIP32Factory(bt).fromSeed(Ef.mnemonicToSeedSync(e));return zx(i,n)}const zx=(e,t)=>{const r=e.derivePath(t).privateKey;if(!r)throw new Error("Unable to derive private key from mnemonic");return r.toString("hex")};oe.initEccLib(bt);class jr extends Mx{constructor({privateKey:t,provider:r,pkPath:n,pkType:i}){const s=Fs.ECPairFactory(bt),o=ma(r.getNetwork()),a=Buffer.from(t,"hex");if(a.length===0)throw new Error("invalid private key");super(),this.minAmt=1e3,this.path=n||"",this.pkType=i,this.signer=s.fromPrivateKey(a,{network:o}),this.provider=r,this.network=o}static fromMnemonic(t,r,n){const i=_y.bip84(r.getNetwork(),n==null?void 0:n.index),s=jx(t,r.getNetwork(),{path:i});return new jr({privateKey:s,provider:r,pkType:fi.p2wpkh,pkPath:i})}static fromPrivateKey(t,r,n){return new jr({privateKey:t,provider:r,pkType:(n==null?void 0:n.pkType)??fi.p2wpkh,pkPath:(n==null?void 0:n.pkPath)??"unknown"})}static createRandom(t){const r=Fs.ECPairFactory(bt),n=ma(t.getNetwork()),i=r.makeRandom({network:n});if(!i.privateKey)throw new Error("Failed to create random key");return new jr({privateKey:i.privateKey.toString("hex"),provider:t,pkType:fi.p2wpkh,pkPath:"unknown"})}static fromWIF(t,r,n){const i=Fs.ECPairFactory(bt),s=ma(r.getNetwork()),o=i.fromWIF(t,s);if(!o.privateKey)throw new Error("Invalid WIF");return jr.fromPrivateKey(o.privateKey.toString("hex"),r,n)}walletConfig(){return{network:this.provider.getNetwork(),path:this.path,addressType:this.pkType}}async spend(t,r,{toAddress:n,fee:i,nSequence:s,unlockScript:o,witness:a}){var y;const c=this.getScriptType(r,this.network),f=await this.provider.getBalance(r);if(f===0)throw new Error(Ur.SCRIPT_NOT_FUNDED);let u=new oe.Transaction;if(u.version=2,i??(i=await this.provider.suggestFee(r,f,In.FAST)),i>f)throw new Error(Ur.FEE_EXCEEDS_AMOUNT(i,f));const d=await this.provider.getUTXOs(r);u=await this.addAllInputs(u,r,this.provider,{nSequence:s,utxos:d}),u.addOutput(await this.toOutputScript(n??await this.getAddress()),f-i);for(let p=0;p<u.ins.length;p++)if(c===Ai.P2SH){if(!o)throw new Error("Unlock script is required for p2sh");const g=[];for(const E of o)if(E instanceof Wr){const A=E.sigHashType,P=u.hashForSignature(p,t,A);g.push(oe.script.signature.encode(Buffer.from(await this.sign(P.toString("hex")),"hex"),A))}else g.push(E);const b=(y=oe.payments.p2sh({redeem:{input:oe.script.compile(g),output:t},network:this.network}).redeem)==null?void 0:y.input;u.setInputScript(p,b)}else if(c===Ai.P2WSH){if(!a)throw new Error("Witness is required for p2wsh");const g=[];for(const b of a)if(b instanceof Wr){const E=b.sigHashType,A=u.hashForWitnessV0(p,t,d[p].value,E);g.push(oe.script.signature.encode(Buffer.from(await this.sign(A.toString("hex")),"hex"),E))}else g.push(b);u.setWitness(p,g)}else throw new Error("Invalid script type "+c);return this.provider.broadcast(u.toHex())}async getAddress(){if(this.pkType===fi["p2wpkh-p2sh"]){const{address:r}=oe.payments.p2sh({redeem:oe.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:t}=oe.payments[this.pkType]({pubkey:this.signer.publicKey,network:this.network});if(!t)throw new Error("failed to get the p2wpkh address");return t}getProvider(){return Promise.resolve(this.provider)}async getBalance(){return this.provider.getBalance(await this.getAddress())}async getPublicKey(){return this.signer.publicKey.toString("hex")}getNetwork(){return Promise.resolve(this.network)}static async generateUnsignedPSBT(t,r,n,i,s,o){if(o||(o=await t.suggestFee(n,s,In.FAST)),o>s)throw new Error(Ur.FEE_EXCEEDS_AMOUNT(o,s));const a=await t.getUTXOs(n,s+o),c=a.reduce((d,y)=>d+y.value,0);if(c<s+o)throw new Error(Ur.INSUFFICIENT_FUNDS(c,s+o));const f=new oe.Psbt({network:r});for(const d of a){const y=await t.getTransactionHex(d.txid);f.addInput({hash:tu(d.txid),index:d.vout,nonWitnessUtxo:Buffer.from(y,"hex")})}const u=c-s-o;return f.addOutput({address:i,value:s}),u>546&&f.addOutput({address:n,value:u}),{txHex:f.toHex(),utxoCount:a.length}}async _send(t,r,n){var f;if(n||(n=await this.provider.suggestFee(await this.getAddress(),r,In.FAST)),n>r)throw new Error(Ur.FEE_EXCEEDS_AMOUNT(n,r));if(r<this.minAmt)throw new Error(Ur.MIN_AMOUNT(this.minAmt));const i=await this.getAddress(),s=await this.provider.getUTXOs(i,r+n),o=s.reduce((u,d)=>u+d.value,0),a=new oe.Psbt({network:this.network});for(const u of s){const d=await this.provider.getTransactionHex(u.txid),y=await this.provider.getTransaction(u.txid);let p;this.pkType===fi["p2wpkh-p2sh"]&&(p={witnessUtxo:{script:Buffer.from(y.vout[u.vout].scriptpubkey,"hex"),value:u.value},redeemScript:(f=oe.payments.p2sh({redeem:oe.payments.p2wpkh({pubkey:this.signer.publicKey,network:this.network}),network:this.network}).redeem)==null?void 0:f.output}),a.addInput({hash:tu(u.txid),index:u.vout,nonWitnessUtxo:Buffer.from(d,"hex"),...p})}const c=o-r-n;return a.addOutput({address:t,value:r}),c>0&&a.addOutput({address:i,value:c}),a.signAllInputs(this.signer).finalizeAllInputs(),a.extractTransaction().toHex()}async send(t,r,n){const i=await this._send(t,r,n);return this.provider.broadcast(i)}async sign(t){return t=t.startsWith("0x")?t.slice(2):t,this.signer.sign(Buffer.from(t,"hex")).toString("hex")}async signSchnorr(t){return this.signer.signSchnorr(t)}}const qx="2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",Gx={name:"solana_native_swaps",version:"0.3.0",spec:"0.1.0",description:"Created with Anchor"},Vx=[{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:[]}],Wx=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],Kx=[{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]}],Yx=[{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"}],Zx=[{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]}}]}}],au={address:qx,metadata:Gx,instructions:Vx,accounts:Wx,events:Kx,errors:Yx,types:Zx};var sr={},jn={};Object.defineProperty(jn,"__esModule",{value:!0});jn.decode=jn.encode=void 0;const Vd=un;function Xx(e){return e.reduce((t,r)=>t+r.toString(16).padStart(2,"0"),"0x")}jn.encode=Xx;function Jx(e){e.indexOf("0x")===0&&(e=e.substr(2)),e.length%2===1&&(e="0"+e);let t=e.match(/.{2}/g);return t===null?Vd.Buffer.from([]):Vd.Buffer.from(t.map(r=>parseInt(r,16)))}jn.decode=Jx;var zn={},Br={},ga;Object.defineProperty(Br,"__esModule",{value:!0});Br.isVersionedTransaction=Br.chunks=Br.isBrowser=void 0;Br.isBrowser=process.env.ANCHOR_BROWSER||typeof window<"u"&&!(!((ga=window.process)===null||ga===void 0)&&ga.hasOwnProperty("type"));function Qx(e,t){return Array.apply(0,new Array(Math.ceil(e.length/t))).map((r,n)=>e.slice(n*t,(n+1)*t))}Br.chunks=Qx;const eA=e=>"version"in e;Br.isVersionedTransaction=eA;var ba={},wa={},va,Wd;function Sy(){return Wd||(Wd=1,va=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var t={},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 i=42;t[r]=i;for(var s in t)return!1;if(typeof Object.keys=="function"&&Object.keys(t).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(t).length!==0)return!1;var o=Object.getOwnPropertySymbols(t);if(o.length!==1||o[0]!==r||!Object.prototype.propertyIsEnumerable.call(t,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var a=Object.getOwnPropertyDescriptor(t,r);if(a.value!==i||a.enumerable!==!0)return!1}return!0}),va}var Ea,Kd;function Fo(){if(Kd)return Ea;Kd=1;var e=Sy();return Ea=function(){return e()&&!!Symbol.toStringTag},Ea}var xa,Yd;function Py(){return Yd||(Yd=1,xa=Object),xa}var Aa,Zd;function tA(){return Zd||(Zd=1,Aa=Error),Aa}var _a,Xd;function rA(){return Xd||(Xd=1,_a=EvalError),_a}var Sa,Jd;function nA(){return Jd||(Jd=1,Sa=RangeError),Sa}var Pa,Qd;function iA(){return Qd||(Qd=1,Pa=ReferenceError),Pa}var Ta,el;function Ty(){return el||(el=1,Ta=SyntaxError),Ta}var Ia,tl;function ls(){return tl||(tl=1,Ia=TypeError),Ia}var ka,rl;function sA(){return rl||(rl=1,ka=URIError),ka}var Ba,nl;function oA(){return nl||(nl=1,Ba=Math.abs),Ba}var Oa,il;function aA(){return il||(il=1,Oa=Math.floor),Oa}var Ca,sl;function cA(){return sl||(sl=1,Ca=Math.max),Ca}var Ra,ol;function uA(){return ol||(ol=1,Ra=Math.min),Ra}var Na,al;function fA(){return al||(al=1,Na=Math.pow),Na}var Fa,cl;function dA(){return cl||(cl=1,Fa=Math.round),Fa}var $a,ul;function lA(){return ul||(ul=1,$a=Number.isNaN||function(t){return t!==t}),$a}var Ua,fl;function pA(){if(fl)return Ua;fl=1;var e=lA();return Ua=function(r){return e(r)||r===0?r:r<0?-1:1},Ua}var Ha,dl;function hA(){return dl||(dl=1,Ha=Object.getOwnPropertyDescriptor),Ha}var La,ll;function Qn(){if(ll)return La;ll=1;var e=hA();if(e)try{e([],"length")}catch{e=null}return La=e,La}var Ma,pl;function $o(){if(pl)return Ma;pl=1;var e=Object.defineProperty||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Ma=e,Ma}var Da,hl;function yA(){if(hl)return Da;hl=1;var e=typeof Symbol<"u"&&Symbol,t=Sy();return Da=function(){return typeof e!="function"||typeof Symbol!="function"||typeof e("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:t()},Da}var ja,yl;function Iy(){return yl||(yl=1,ja=typeof Reflect<"u"&&Reflect.getPrototypeOf||null),ja}var za,ml;function ky(){if(ml)return za;ml=1;var e=Py();return za=e.getPrototypeOf||null,za}var qa,gl;function mA(){if(gl)return qa;gl=1;var e="Function.prototype.bind called on incompatible ",t=Object.prototype.toString,r=Math.max,n="[object Function]",i=function(c,f){for(var u=[],d=0;d<c.length;d+=1)u[d]=c[d];for(var y=0;y<f.length;y+=1)u[y+c.length]=f[y];return u},s=function(c,f){for(var u=[],d=f,y=0;d<c.length;d+=1,y+=1)u[y]=c[d];return u},o=function(a,c){for(var f="",u=0;u<a.length;u+=1)f+=a[u],u+1<a.length&&(f+=c);return f};return qa=function(c){var f=this;if(typeof f!="function"||t.apply(f)!==n)throw new TypeError(e+f);for(var u=s(arguments,1),d,y=function(){if(this instanceof d){var A=f.apply(this,i(u,arguments));return Object(A)===A?A:this}return f.apply(c,i(u,arguments))},p=r(0,f.length-u.length),g=[],b=0;b<p;b++)g[b]="$"+b;if(d=Function("binder","return function ("+o(g,",")+"){ return binder.apply(this,arguments); }")(y),f.prototype){var E=function(){};E.prototype=f.prototype,d.prototype=new E,E.prototype=null}return d},qa}var Ga,bl;function ps(){if(bl)return Ga;bl=1;var e=mA();return Ga=Function.prototype.bind||e,Ga}var Va,wl;function yf(){return wl||(wl=1,Va=Function.prototype.call),Va}var Wa,vl;function mf(){return vl||(vl=1,Wa=Function.prototype.apply),Wa}var Ka,El;function gA(){return El||(El=1,Ka=typeof Reflect<"u"&&Reflect&&Reflect.apply),Ka}var Ya,xl;function By(){if(xl)return Ya;xl=1;var e=ps(),t=mf(),r=yf(),n=gA();return Ya=n||e.call(r,t),Ya}var Za,Al;function gf(){if(Al)return Za;Al=1;var e=ps(),t=ls(),r=yf(),n=By();return Za=function(s){if(s.length<1||typeof s[0]!="function")throw new t("a function is required");return n(e,r,s)},Za}var Xa,_l;function bA(){if(_l)return Xa;_l=1;var e=gf(),t=Qn(),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&&t&&t(Object.prototype,"__proto__"),i=Object,s=i.getPrototypeOf;return Xa=n&&typeof n.get=="function"?e([n.get]):typeof s=="function"?function(a){return s(a==null?a:i(a))}:!1,Xa}var Ja,Sl;function bf(){if(Sl)return Ja;Sl=1;var e=Iy(),t=ky(),r=bA();return Ja=e?function(i){return e(i)}:t?function(i){if(!i||typeof i!="object"&&typeof i!="function")throw new TypeError("getProto: not an object");return t(i)}:r?function(i){return r(i)}:null,Ja}var Qa,Pl;function Oy(){if(Pl)return Qa;Pl=1;var e=Function.prototype.call,t=Object.prototype.hasOwnProperty,r=ps();return Qa=r.call(e,t),Qa}var ec,Tl;function Cy(){if(Tl)return ec;Tl=1;var e,t=Py(),r=tA(),n=rA(),i=nA(),s=iA(),o=Ty(),a=ls(),c=sA(),f=oA(),u=aA(),d=cA(),y=uA(),p=fA(),g=dA(),b=pA(),E=Function,A=function(re){try{return E('"use strict"; return ('+re+").constructor;")()}catch{}},P=Qn(),w=$o(),_=function(){throw new a},T=P?function(){try{return arguments.callee,_}catch{try{return P(arguments,"callee").get}catch{return _}}}():_,I=yA()(),R=bf(),L=ky(),S=Iy(),$=mf(),C=yf(),U={},j=typeof Uint8Array>"u"||!R?e:R(Uint8Array),V={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?e:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?e:ArrayBuffer,"%ArrayIteratorPrototype%":I&&R?R([][Symbol.iterator]()):e,"%AsyncFromSyncIteratorPrototype%":e,"%AsyncFunction%":U,"%AsyncGenerator%":U,"%AsyncGeneratorFunction%":U,"%AsyncIteratorPrototype%":U,"%Atomics%":typeof Atomics>"u"?e:Atomics,"%BigInt%":typeof BigInt>"u"?e:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?e:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?e:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?e:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":r,"%eval%":eval,"%EvalError%":n,"%Float16Array%":typeof Float16Array>"u"?e:Float16Array,"%Float32Array%":typeof Float32Array>"u"?e:Float32Array,"%Float64Array%":typeof Float64Array>"u"?e:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?e:FinalizationRegistry,"%Function%":E,"%GeneratorFunction%":U,"%Int8Array%":typeof Int8Array>"u"?e:Int8Array,"%Int16Array%":typeof Int16Array>"u"?e:Int16Array,"%Int32Array%":typeof Int32Array>"u"?e:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":I&&R?R(R([][Symbol.iterator]())):e,"%JSON%":typeof JSON=="object"?JSON:e,"%Map%":typeof Map>"u"?e:Map,"%MapIteratorPrototype%":typeof Map>"u"||!I||!R?e:R(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":t,"%Object.getOwnPropertyDescriptor%":P,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?e:Promise,"%Proxy%":typeof Proxy>"u"?e:Proxy,"%RangeError%":i,"%ReferenceError%":s,"%Reflect%":typeof Reflect>"u"?e:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?e:Set,"%SetIteratorPrototype%":typeof Set>"u"||!I||!R?e:R(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?e:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":I&&R?R(""[Symbol.iterator]()):e,"%Symbol%":I?Symbol:e,"%SyntaxError%":o,"%ThrowTypeError%":T,"%TypedArray%":j,"%TypeError%":a,"%Uint8Array%":typeof Uint8Array>"u"?e:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?e:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?e:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?e:Uint32Array,"%URIError%":c,"%WeakMap%":typeof WeakMap>"u"?e:WeakMap,"%WeakRef%":typeof WeakRef>"u"?e:WeakRef,"%WeakSet%":typeof WeakSet>"u"?e:WeakSet,"%Function.prototype.call%":C,"%Function.prototype.apply%":$,"%Object.defineProperty%":w,"%Object.getPrototypeOf%":L,"%Math.abs%":f,"%Math.floor%":u,"%Math.max%":d,"%Math.min%":y,"%Math.pow%":p,"%Math.round%":g,"%Math.sign%":b,"%Reflect.getPrototypeOf%":S};if(R)try{null.error}catch(re){var Y=R(R(re));V["%Error.prototype%"]=Y}var X=function re(te){var se;if(te==="%AsyncFunction%")se=A("async function () {}");else if(te==="%GeneratorFunction%")se=A("function* () {}");else if(te==="%AsyncGeneratorFunction%")se=A("async function* () {}");else if(te==="%AsyncGenerator%"){var de=re("%AsyncGeneratorFunction%");de&&(se=de.prototype)}else if(te==="%AsyncIteratorPrototype%"){var he=re("%AsyncGenerator%");he&&R&&(se=R(he.prototype))}return V[te]=se,se},J={__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"]},M=ps(),B=Oy(),q=M.call(C,Array.prototype.concat),W=M.call($,Array.prototype.splice),k=M.call(C,String.prototype.replace),N=M.call(C,String.prototype.slice),H=M.call(C,RegExp.prototype.exec),Z=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,Q=/\\(\\)?/g,ie=function(te){var se=N(te,0,1),de=N(te,-1);if(se==="%"&&de!=="%")throw new o("invalid intrinsic syntax, expected closing `%`");if(de==="%"&&se!=="%")throw new o("invalid intrinsic syntax, expected opening `%`");var he=[];return k(te,Z,function(Ae,ot,Re,Rt){he[he.length]=Re?k(Rt,Q,"$1"):ot||Ae}),he},ne=function(te,se){var de=te,he;if(B(J,de)&&(he=J[de],de="%"+he[0]+"%"),B(V,de)){var Ae=V[de];if(Ae===U&&(Ae=X(de)),typeof Ae>"u"&&!se)throw new a("intrinsic "+te+" exists, but is not available. Please file an issue!");return{alias:he,name:de,value:Ae}}throw new o("intrinsic "+te+" does not exist!")};return ec=function(te,se){if(typeof te!="string"||te.length===0)throw new a("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof se!="boolean")throw new a('"allowMissing" argument must be a boolean');if(H(/^%?[^%]*%?$/,te)===null)throw new o("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var de=ie(te),he=de.length>0?de[0]:"",Ae=ne("%"+he+"%",se),ot=Ae.name,Re=Ae.value,Rt=!1,Fr=Ae.alias;Fr&&(he=Fr[0],W(de,q([0,1],Fr)));for(var G=1,Nt=!0;G<de.length;G+=1){var Ge=de[G],Ve=N(Ge,0,1),hr=N(Ge,-1);if((Ve==='"'||Ve==="'"||Ve==="`"||hr==='"'||hr==="'"||hr==="`")&&Ve!==hr)throw new o("property names with quotes must have matching quotes");if((Ge==="constructor"||!Nt)&&(Rt=!0),he+="."+Ge,ot="%"+he+"%",B(V,ot))Re=V[ot];else if(Re!=null){if(!(Ge in Re)){if(!se)throw new a("base intrinsic for "+te+" exists, but the property is not available.");return}if(P&&G+1>=de.length){var ln=P(Re,Ge);Nt=!!ln,Nt&&"get"in ln&&!("originalValue"in ln.get)?Re=ln.get:Re=Re[Ge]}else Nt=B(Re,Ge),Re=Re[Ge];Nt&&!Rt&&(V[ot]=Re)}}return Re},ec}var tc,Il;function hs(){if(Il)return tc;Il=1;var e=Cy(),t=gf(),r=t([e("%String.prototype.indexOf%")]);return tc=function(i,s){var o=e(i,!!s);return typeof o=="function"&&r(i,".prototype.")>-1?t([o]):o},tc}var rc,kl;function wA(){if(kl)return rc;kl=1;var e=Fo()(),t=hs(),r=t("Object.prototype.toString"),n=function(a){return e&&a&&typeof a=="object"&&Symbol.toStringTag in a?!1:r(a)==="[object Arguments]"},i=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]"},s=function(){return n(arguments)}();return n.isLegacyArguments=i,rc=s?n:i,rc}var nc,Bl;function vA(){if(Bl)return nc;Bl=1;var e=hs(),t=Fo()(),r=Oy(),n=Qn(),i;if(t){var s=e("RegExp.prototype.exec"),o={},a=function(){throw o},c={toString:a,valueOf:a};typeof Symbol.toPrimitive=="symbol"&&(c[Symbol.toPrimitive]=a),i=function(y){if(!y||typeof y!="object")return!1;var p=n(y,"lastIndex"),g=p&&r(p,"value");if(!g)return!1;try{s(y,c)}catch(b){return b===o}}}else{var f=e("Object.prototype.toString"),u="[object RegExp]";i=function(y){return!y||typeof y!="object"&&typeof y!="function"?!1:f(y)===u}}return nc=i,nc}var ic,Ol;function EA(){if(Ol)return ic;Ol=1;var e=hs(),t=vA(),r=e("RegExp.prototype.exec"),n=ls();return ic=function(s){if(!t(s))throw new n("`regex` must be a RegExp");return function(a){return r(s,a)!==null}},ic}var sc,Cl;function xA(){if(Cl)return sc;Cl=1;var e=hs(),t=EA(),r=t(/^\s*(?:function)?\*/),n=Fo()(),i=bf(),s=e("Object.prototype.toString"),o=e("Function.prototype.toString"),a=function(){if(!n)return!1;try{return Function("return function*() {}")()}catch{}},c;return sc=function(u){if(typeof u!="function")return!1;if(r(o(u)))return!0;if(!n){var d=s(u);return d==="[object GeneratorFunction]"}if(!i)return!1;if(typeof c>"u"){var y=a();c=y?i(y):!1}return i(u)===c},sc}var oc,Rl;function AA(){if(Rl)return oc;Rl=1;var e=Function.prototype.toString,t=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,r,n;if(typeof t=="function"&&typeof Object.defineProperty=="function")try{r=Object.defineProperty({},"length",{get:function(){throw n}}),n={},t(function(){throw 42},null,r)}catch(P){P!==n&&(t=null)}else t=null;var i=/^\s*class\b/,s=function(w){try{var _=e.call(w);return i.test(_)}catch{return!1}},o=function(w){try{return s(w)?!1:(e.call(w),!0)}catch{return!1}},a=Object.prototype.toString,c="[object Object]",f="[object Function]",u="[object GeneratorFunction]",d="[object HTMLAllCollection]",y="[object HTML document.all class]",p="[object HTMLCollection]",g=typeof Symbol=="function"&&!!Symbol.toStringTag,b=!(0 in[,]),E=function(){return!1};if(typeof document=="object"){var A=document.all;a.call(A)===a.call(document.all)&&(E=function(w){if((b||!w)&&(typeof w>"u"||typeof w=="object"))try{var _=a.call(w);return(_===d||_===y||_===p||_===c)&&w("")==null}catch{}return!1})}return oc=t?function(w){if(E(w))return!0;if(!w||typeof w!="function"&&typeof w!="object")return!1;try{t(w,null,r)}catch(_){if(_!==n)return!1}return!s(w)&&o(w)}:function(w){if(E(w))return!0;if(!w||typeof w!="function"&&typeof w!="object")return!1;if(g)return o(w);if(s(w))return!1;var _=a.call(w);return _!==f&&_!==u&&!/^\[object HTML/.test(_)?!1:o(w)},oc}var ac,Nl;function _A(){if(Nl)return ac;Nl=1;var e=AA(),t=Object.prototype.toString,r=Object.prototype.hasOwnProperty,n=function(c,f,u){for(var d=0,y=c.length;d<y;d++)r.call(c,d)&&(u==null?f(c[d],d,c):f.call(u,c[d],d,c))},i=function(c,f,u){for(var d=0,y=c.length;d<y;d++)u==null?f(c.charAt(d),d,c):f.call(u,c.charAt(d),d,c)},s=function(c,f,u){for(var d in c)r.call(c,d)&&(u==null?f(c[d],d,c):f.call(u,c[d],d,c))};function o(a){return t.call(a)==="[object Array]"}return ac=function(c,f,u){if(!e(f))throw new TypeError("iterator must be a function");var d;arguments.length>=3&&(d=u),o(c)?n(c,f,d):typeof c=="string"?i(c,f,d):s(c,f,d)},ac}var cc,Fl;function SA(){return Fl||(Fl=1,cc=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]),cc}var uc,$l;function PA(){if($l)return uc;$l=1;var e=SA(),t=typeof globalThis>"u"?Kt:globalThis;return uc=function(){for(var n=[],i=0;i<e.length;i++)typeof t[e[i]]=="function"&&(n[n.length]=e[i]);return n},uc}var fc={exports:{}},dc,Ul;function TA(){if(Ul)return dc;Ul=1;var e=$o(),t=Ty(),r=ls(),n=Qn();return dc=function(s,o,a){if(!s||typeof s!="object"&&typeof s!="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,f=arguments.length>4?arguments[4]:null,u=arguments.length>5?arguments[5]:null,d=arguments.length>6?arguments[6]:!1,y=!!n&&n(s,o);if(e)e(s,o,{configurable:u===null&&y?y.configurable:!u,enumerable:c===null&&y?y.enumerable:!c,value:a,writable:f===null&&y?y.writable:!f});else if(d||!c&&!f&&!u)s[o]=a;else throw new t("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},dc}var lc,Hl;function IA(){if(Hl)return lc;Hl=1;var e=$o(),t=function(){return!!e};return t.hasArrayLengthDefineBug=function(){if(!e)return null;try{return e([],"length",{value:1}).length!==1}catch{return!0}},lc=t,lc}var pc,Ll;function kA(){if(Ll)return pc;Ll=1;var e=Cy(),t=TA(),r=IA()(),n=Qn(),i=ls(),s=e("%Math.floor%");return pc=function(a,c){if(typeof a!="function")throw new i("`fn` is not a function");if(typeof c!="number"||c<0||c>4294967295||s(c)!==c)throw new i("`length` must be a positive 32-bit integer");var f=arguments.length>2&&!!arguments[2],u=!0,d=!0;if("length"in a&&n){var y=n(a,"length");y&&!y.configurable&&(u=!1),y&&!y.writable&&(d=!1)}return(u||d||!f)&&(r?t(a,"length",c,!0,!0):t(a,"length",c)),a},pc}var hc,Ml;function BA(){if(Ml)return hc;Ml=1;var e=ps(),t=mf(),r=By();return hc=function(){return r(e,t,arguments)},hc}var Dl;function OA(){return Dl||(Dl=1,function(e){var t=kA(),r=$o(),n=gf(),i=BA();e.exports=function(o){var a=n(arguments),c=o.length-(arguments.length-1);return t(a,1+(c>0?c:0),!0)},r?r(e.exports,"apply",{value:i}):e.exports.apply=i}(fc)),fc.exports}var yc,jl;function Ry(){if(jl)return yc;jl=1;var e=_A(),t=PA(),r=OA(),n=hs(),i=Qn(),s=bf(),o=n("Object.prototype.toString"),a=Fo()(),c=typeof globalThis>"u"?Kt:globalThis,f=t(),u=n("String.prototype.slice"),d=n("Array.prototype.indexOf",!0)||function(E,A){for(var P=0;P<E.length;P+=1)if(E[P]===A)return P;return-1},y={__proto__:null};a&&i&&s?e(f,function(b){var E=new c[b];if(Symbol.toStringTag in E&&s){var A=s(E),P=i(A,Symbol.toStringTag);if(!P&&A){var w=s(A);P=i(w,Symbol.toStringTag)}y["$"+b]=r(P.get)}}):e(f,function(b){var E=new c[b],A=E.slice||E.set;A&&(y["$"+b]=r(A))});var p=function(E){var A=!1;return e(y,function(P,w){if(!A)try{"$"+P(E)===w&&(A=u(w,1))}catch{}}),A},g=function(E){var A=!1;return e(y,function(P,w){if(!A)try{P(E),A=u(w,1)}catch{}}),A};return yc=function(E){if(!E||typeof E!="object")return!1;if(!a){var A=u(o(E),8,-1);return d(f,A)>-1?A:A!=="Object"?!1:g(E)}return i?p(E):null},yc}var mc,zl;function CA(){if(zl)return mc;zl=1;var e=Ry();return mc=function(r){return!!e(r)},mc}var ql;function RA(){return ql||(ql=1,function(e){var t=wA(),r=xA(),n=Ry(),i=CA();function s(G){return G.call.bind(G)}var o=typeof BigInt<"u",a=typeof Symbol<"u",c=s(Object.prototype.toString),f=s(Number.prototype.valueOf),u=s(String.prototype.valueOf),d=s(Boolean.prototype.valueOf);if(o)var y=s(BigInt.prototype.valueOf);if(a)var p=s(Symbol.prototype.valueOf);function g(G,Nt){if(typeof G!="object")return!1;try{return Nt(G),!0}catch{return!1}}e.isArgumentsObject=t,e.isGeneratorFunction=r,e.isTypedArray=i;function b(G){return typeof Promise<"u"&&G instanceof Promise||G!==null&&typeof G=="object"&&typeof G.then=="function"&&typeof G.catch=="function"}e.isPromise=b;function E(G){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(G):i(G)||N(G)}e.isArrayBufferView=E;function A(G){return n(G)==="Uint8Array"}e.isUint8Array=A;function P(G){return n(G)==="Uint8ClampedArray"}e.isUint8ClampedArray=P;function w(G){return n(G)==="Uint16Array"}e.isUint16Array=w;function _(G){return n(G)==="Uint32Array"}e.isUint32Array=_;function T(G){return n(G)==="Int8Array"}e.isInt8Array=T;function I(G){return n(G)==="Int16Array"}e.isInt16Array=I;function R(G){return n(G)==="Int32Array"}e.isInt32Array=R;function L(G){return n(G)==="Float32Array"}e.isFloat32Array=L;function S(G){return n(G)==="Float64Array"}e.isFloat64Array=S;function $(G){return n(G)==="BigInt64Array"}e.isBigInt64Array=$;function C(G){return n(G)==="BigUint64Array"}e.isBigUint64Array=C;function U(G){return c(G)==="[object Map]"}U.working=typeof Map<"u"&&U(new Map);function j(G){return typeof Map>"u"?!1:U.working?U(G):G instanceof Map}e.isMap=j;function V(G){return c(G)==="[object Set]"}V.working=typeof Set<"u"&&V(new Set);function Y(G){return typeof Set>"u"?!1:V.working?V(G):G instanceof Set}e.isSet=Y;function X(G){return c(G)==="[object WeakMap]"}X.working=typeof WeakMap<"u"&&X(new WeakMap);function J(G){return typeof WeakMap>"u"?!1:X.working?X(G):G instanceof WeakMap}e.isWeakMap=J;function M(G){return c(G)==="[object WeakSet]"}M.working=typeof WeakSet<"u"&&M(new WeakSet);function B(G){return M(G)}e.isWeakSet=B;function q(G){return c(G)==="[object ArrayBuffer]"}q.working=typeof ArrayBuffer<"u"&&q(new ArrayBuffer);function W(G){return typeof ArrayBuffer>"u"?!1:q.working?q(G):G instanceof ArrayBuffer}e.isArrayBuffer=W;function k(G){return c(G)==="[object DataView]"}k.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&k(new DataView(new ArrayBuffer(1),0,1));function N(G){return typeof DataView>"u"?!1:k.working?k(G):G instanceof DataView}e.isDataView=N;var H=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function Z(G){return c(G)==="[object SharedArrayBuffer]"}function Q(G){return typeof H>"u"?!1:(typeof Z.working>"u"&&(Z.working=Z(new H)),Z.working?Z(G):G instanceof H)}e.isSharedArrayBuffer=Q;function ie(G){return c(G)==="[object AsyncFunction]"}e.isAsyncFunction=ie;function ne(G){return c(G)==="[object Map Iterator]"}e.isMapIterator=ne;function re(G){return c(G)==="[object Set Iterator]"}e.isSetIterator=re;function te(G){return c(G)==="[object Generator]"}e.isGeneratorObject=te;function se(G){return c(G)==="[object WebAssembly.Module]"}e.isWebAssemblyCompiledModule=se;function de(G){return g(G,f)}e.isNumberObject=de;function he(G){return g(G,u)}e.isStringObject=he;function Ae(G){return g(G,d)}e.isBooleanObject=Ae;function ot(G){return o&&g(G,y)}e.isBigIntObject=ot;function Re(G){return a&&g(G,p)}e.isSymbolObject=Re;function Rt(G){return de(G)||he(G)||Ae(G)||ot(G)||Re(G)}e.isBoxedPrimitive=Rt;function Fr(G){return typeof Uint8Array<"u"&&(W(G)||Q(G))}e.isAnyArrayBuffer=Fr,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(G){Object.defineProperty(e,G,{enumerable:!1,value:function(){throw new Error(G+" is not supported in userland")}})})}(wa)),wa}var gc,Gl;function NA(){return Gl||(Gl=1,gc=function(t){return t&&typeof t=="object"&&typeof t.copy=="function"&&typeof t.fill=="function"&&typeof t.readUInt8=="function"}),gc}var Rs={exports:{}},Vl;function FA(){return Vl||(Vl=1,typeof Object.create=="function"?Rs.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:Rs.exports=function(t,r){if(r){t.super_=r;var n=function(){};n.prototype=r.prototype,t.prototype=new n,t.prototype.constructor=t}}),Rs.exports}var Wl;function Ny(){return Wl||(Wl=1,function(e){var t=Object.getOwnPropertyDescriptors||function(N){for(var H=Object.keys(N),Z={},Q=0;Q<H.length;Q++)Z[H[Q]]=Object.getOwnPropertyDescriptor(N,H[Q]);return Z},r=/%[sdj%]/g;e.format=function(k){if(!T(k)){for(var N=[],H=0;H<arguments.length;H++)N.push(o(arguments[H]));return N.join(" ")}for(var H=1,Z=arguments,Q=Z.length,ie=String(k).replace(r,function(re){if(re==="%%")return"%";if(H>=Q)return re;switch(re){case"%s":return String(Z[H++]);case"%d":return Number(Z[H++]);case"%j":try{return JSON.stringify(Z[H++])}catch{return"[Circular]"}default:return re}}),ne=Z[H];H<Q;ne=Z[++H])P(ne)||!S(ne)?ie+=" "+ne:ie+=" "+o(ne);return ie},e.deprecate=function(k,N){if(typeof process<"u"&&process.noDeprecation===!0)return k;if(typeof process>"u")return function(){return e.deprecate(k,N).apply(this,arguments)};var H=!1;function Z(){if(!H){if(process.throwDeprecation)throw new Error(N);process.traceDeprecation?console.trace(N):console.error(N),H=!0}return k.apply(this,arguments)}return Z};var n={},i=/^$/;if(process.env.NODE_DEBUG){var s=process.env.NODE_DEBUG;s=s.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),i=new RegExp("^"+s+"$","i")}e.debuglog=function(k){if(k=k.toUpperCase(),!n[k])if(i.test(k)){var N=process.pid;n[k]=function(){var H=e.format.apply(e,arguments);console.error("%s %d: %s",k,N,H)}}else n[k]=function(){};return n[k]};function o(k,N){var H={seen:[],stylize:c};return arguments.length>=3&&(H.depth=arguments[2]),arguments.length>=4&&(H.colors=arguments[3]),A(N)?H.showHidden=N:N&&e._extend(H,N),R(H.showHidden)&&(H.showHidden=!1),R(H.depth)&&(H.depth=2),R(H.colors)&&(H.colors=!1),R(H.customInspect)&&(H.customInspect=!0),H.colors&&(H.stylize=a),u(H,k,H.depth)}e.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(k,N){var H=o.styles[N];return H?"\x1B["+o.colors[H][0]+"m"+k+"\x1B["+o.colors[H][1]+"m":k}function c(k,N){return k}function f(k){var N={};return k.forEach(function(H,Z){N[H]=!0}),N}function u(k,N,H){if(k.customInspect&&N&&U(N.inspect)&&N.inspect!==e.inspect&&!(N.constructor&&N.constructor.prototype===N)){var Z=N.inspect(H,k);return T(Z)||(Z=u(k,Z,H)),Z}var Q=d(k,N);if(Q)return Q;var ie=Object.keys(N),ne=f(ie);if(k.showHidden&&(ie=Object.getOwnPropertyNames(N)),C(N)&&(ie.indexOf("message")>=0||ie.indexOf("description")>=0))return y(N);if(ie.length===0){if(U(N)){var re=N.name?": "+N.name:"";return k.stylize("[Function"+re+"]","special")}if(L(N))return k.stylize(RegExp.prototype.toString.call(N),"regexp");if($(N))return k.stylize(Date.prototype.toString.call(N),"date");if(C(N))return y(N)}var te="",se=!1,de=["{","}"];if(E(N)&&(se=!0,de=["[","]"]),U(N)){var he=N.name?": "+N.name:"";te=" [Function"+he+"]"}if(L(N)&&(te=" "+RegExp.prototype.toString.call(N)),$(N)&&(te=" "+Date.prototype.toUTCString.call(N)),C(N)&&(te=" "+y(N)),ie.length===0&&(!se||N.length==0))return de[0]+te+de[1];if(H<0)return L(N)?k.stylize(RegExp.prototype.toString.call(N),"regexp"):k.stylize("[Object]","special");k.seen.push(N);var Ae;return se?Ae=p(k,N,H,ne,ie):Ae=ie.map(function(ot){return g(k,N,H,ne,ot,se)}),k.seen.pop(),b(Ae,te,de)}function d(k,N){if(R(N))return k.stylize("undefined","undefined");if(T(N)){var H="'"+JSON.stringify(N).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return k.stylize(H,"string")}if(_(N))return k.stylize(""+N,"number");if(A(N))return k.stylize(""+N,"boolean");if(P(N))return k.stylize("null","null")}function y(k){return"["+Error.prototype.toString.call(k)+"]"}function p(k,N,H,Z,Q){for(var ie=[],ne=0,re=N.length;ne<re;++ne)M(N,String(ne))?ie.push(g(k,N,H,Z,String(ne),!0)):ie.push("");return Q.forEach(function(te){te.match(/^\d+$/)||ie.push(g(k,N,H,Z,te,!0))}),ie}function g(k,N,H,Z,Q,ie){var ne,re,te;if(te=Object.getOwnPropertyDescriptor(N,Q)||{value:N[Q]},te.get?te.set?re=k.stylize("[Getter/Setter]","special"):re=k.stylize("[Getter]","special"):te.set&&(re=k.stylize("[Setter]","special")),M(Z,Q)||(ne="["+Q+"]"),re||(k.seen.indexOf(te.value)<0?(P(H)?re=u(k,te.value,null):re=u(k,te.value,H-1),re.indexOf(`
90
+ `.trim().replace(/\s+/g," ")),s=oe.payments[r?"p2sh":"p2wsh"]({redeem:{output:i},network:t});if(!s.address)throw new Error("Could not build address");return{script:i,address:s.address}},Ai={P2SH:"p2sh",P2WSH:"p2wsh",P2TR:"p2tr"};var Ay=(e=>(e[e.Bitcoin=0]="Bitcoin",e[e.EVM=1]="EVM",e))(Ay||{});class jx{addSignatureSegwitV0(t=qs.ALL){return new Wr("segwitV0",t)}addSignatureP2sh(t=qs.ALL){return new Wr("p2shSignature",t)}addSignatureSegwitV1(t=qs.ALL){return new Wr("segwitV1",t)}chain(){return Ay.Bitcoin}async addAllInputs(t,r,n,i){const s=(i==null?void 0:i.utxos)||await n.getUTXOs(r);for(const o of s){const a=await n.getTxIndex(o.txid,r);t.addInput(tu(o.txid),a,i==null?void 0:i.nSequence)}return t}async suggestFee(t,r){const n=await this.getAddress();return(await this.getProvider()).suggestFee(n,t,r)}async toOutputScript(t){return oe.address.toOutputScript(t,await this.getNetwork())}totalValueFromUTXOs(t){return t.reduce((r,n)=>r+n.value,0)}async scriptToAddress(t){const r=oe.payments.p2wsh({redeem:{output:t},network:await this.getNetwork()});if(!r.address)throw new Error("Could not generate p2wsh address");return r.address}async newSwap(t){if(t.secretHash=x.trim0x(t.secretHash),t.secretHash.length!==64)throw new Error(yi.INVALID_SECRET_HASH);const{script:r,address:n}=Dx(t,await this.getNetwork());return new zx(this,{...t,redeemScript:r,scriptAddress:n})}getScriptType(t,r){try{if(oe.address.fromBase58Check(t).version===r.scriptHash)return Ai.P2SH}catch{const i=oe.address.fromBech32(t);if(i.prefix!==r.bech32)throw new Error("Invalid address");if(i.version===0){if(i.data.length===32)return Ai.P2WSH}else if(i.version===1&&i.data.length===32)return Ai.P2TR}throw new Error("Unsupported script type")}}class zx{constructor(t,r){if(r.secretHash=x.trim0x(r.secretHash),r.secretHash.length!==64)throw new Error(yi.INVALID_SECRET_HASH);this.wallet=t,this.swap=r}id(){return this.swap.scriptAddress}async init(){return this.wallet.send(this.swap.scriptAddress,+this.swap.amount.toString())}async redeem(t,r){t=x.trim0x(t);const n=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),Buffer.from(t,"hex"),oe.script.number.encode(1),this.swap.redeemScript],i=oe.payments.p2wsh({redeem:{output:this.swap.redeemScript},network:await this.wallet.getNetwork()}).address;if(!i)throw new Error("Could not generate p2wsh address for redeem script");try{return await this.wallet.spend(this.swap.redeemScript,i,{witness:n,toAddress:r})}catch(s){throw ru(s)?s.message.includes("OP_EQUALVERIFY")?new Error(yi.INVALID_PUBKEY_OR_SECRET):new Error(s.message):new Error(String(s))}}async refund(t){const r=[this.wallet.addSignatureSegwitV0(),Buffer.from(await this.wallet.getPublicKey(),"hex"),oe.script.number.encode(0),this.swap.redeemScript];try{const n=oe.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:t,witness:r,nSequence:this.swap.expiryBlocks})}catch(n){throw ru(n)?n.message.includes("OP_EQUALVERIFY")?new Error(yi.INVALID_PUBKEY):n.message.includes("BIP")?new Error(yi.ORDER_NOT_EXPIRED):new Error(n.message):new Error(String(n))}}}const ya=(e,t,r,n)=>`m/${e}'/${t===ct.Mainnet?0:1}'/${r}'/0/${n??0}`,_y={bip44:(e,t,r)=>ya("44",e,r??0,t),bip49:(e,t,r)=>ya("49",e,r??0,t),bip84:(e,t,r)=>ya("84",e,r??0,t)};function ma(e){if(e===ct.Mainnet)return oe.networks.bitcoin;if(e===ct.Testnet)return oe.networks.testnet;if(e===ct.Regtest)return oe.networks.regtest;throw new Error("Invalid network")}function qx(e,t,r){if(!Ef.validateMnemonic(e))throw new Error("Invalid mnemonic");const n=(r==null?void 0:r.path)??_y.bip44(t,(r==null?void 0:r.index)??0),i=jy.BIP32Factory(wt).fromSeed(Ef.mnemonicToSeedSync(e));return Gx(i,n)}const Gx=(e,t)=>{const r=e.derivePath(t).privateKey;if(!r)throw new Error("Unable to derive private key from mnemonic");return r.toString("hex")};oe.initEccLib(wt);class jr extends jx{constructor({privateKey:t,provider:r,pkPath:n,pkType:i}){const s=Fs.ECPairFactory(wt),o=ma(r.getNetwork()),a=Buffer.from(t,"hex");if(a.length===0)throw new Error("invalid private key");super(),this.minAmt=1e3,this.path=n||"",this.pkType=i,this.signer=s.fromPrivateKey(a,{network:o}),this.provider=r,this.network=o}static fromMnemonic(t,r,n){const i=_y.bip84(r.getNetwork(),n==null?void 0:n.index),s=qx(t,r.getNetwork(),{path:i});return new jr({privateKey:s,provider:r,pkType:fi.p2wpkh,pkPath:i})}static fromPrivateKey(t,r,n){return new jr({privateKey:t,provider:r,pkType:(n==null?void 0:n.pkType)??fi.p2wpkh,pkPath:(n==null?void 0:n.pkPath)??"unknown"})}static createRandom(t){const r=Fs.ECPairFactory(wt),n=ma(t.getNetwork()),i=r.makeRandom({network:n});if(!i.privateKey)throw new Error("Failed to create random key");return new jr({privateKey:i.privateKey.toString("hex"),provider:t,pkType:fi.p2wpkh,pkPath:"unknown"})}static fromWIF(t,r,n){const i=Fs.ECPairFactory(wt),s=ma(r.getNetwork()),o=i.fromWIF(t,s);if(!o.privateKey)throw new Error("Invalid WIF");return jr.fromPrivateKey(o.privateKey.toString("hex"),r,n)}walletConfig(){return{network:this.provider.getNetwork(),path:this.path,addressType:this.pkType}}async spend(t,r,{toAddress:n,fee:i,nSequence:s,unlockScript:o,witness:a}){var y;const c=this.getScriptType(r,this.network),f=await this.provider.getBalance(r);if(f===0)throw new Error(Ur.SCRIPT_NOT_FUNDED);let u=new oe.Transaction;if(u.version=2,i??(i=await this.provider.suggestFee(r,f,In.FAST)),i>f)throw new Error(Ur.FEE_EXCEEDS_AMOUNT(i,f));const d=await this.provider.getUTXOs(r);u=await this.addAllInputs(u,r,this.provider,{nSequence:s,utxos:d}),u.addOutput(await this.toOutputScript(n??await this.getAddress()),f-i);for(let p=0;p<u.ins.length;p++)if(c===Ai.P2SH){if(!o)throw new Error("Unlock script is required for p2sh");const g=[];for(const E of o)if(E instanceof Wr){const A=E.sigHashType,P=u.hashForSignature(p,t,A);g.push(oe.script.signature.encode(Buffer.from(await this.sign(P.toString("hex")),"hex"),A))}else g.push(E);const b=(y=oe.payments.p2sh({redeem:{input:oe.script.compile(g),output:t},network:this.network}).redeem)==null?void 0:y.input;u.setInputScript(p,b)}else if(c===Ai.P2WSH){if(!a)throw new Error("Witness is required for p2wsh");const g=[];for(const b of a)if(b instanceof Wr){const E=b.sigHashType,A=u.hashForWitnessV0(p,t,d[p].value,E);g.push(oe.script.signature.encode(Buffer.from(await this.sign(A.toString("hex")),"hex"),E))}else g.push(b);u.setWitness(p,g)}else throw new Error("Invalid script type "+c);return this.provider.broadcast(u.toHex())}async getAddress(){if(this.pkType===fi["p2wpkh-p2sh"]){const{address:r}=oe.payments.p2sh({redeem:oe.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:t}=oe.payments[this.pkType]({pubkey:this.signer.publicKey,network:this.network});if(!t)throw new Error("failed to get the p2wpkh address");return t}getProvider(){return Promise.resolve(this.provider)}async getBalance(){return this.provider.getBalance(await this.getAddress())}async getPublicKey(){return this.signer.publicKey.toString("hex")}getNetwork(){return Promise.resolve(this.network)}static async generateUnsignedPSBT(t,r,n,i,s,o){if(o||(o=await t.suggestFee(n,s,In.FAST)),o>s)throw new Error(Ur.FEE_EXCEEDS_AMOUNT(o,s));const a=await t.getUTXOs(n,s+o),c=a.reduce((d,y)=>d+y.value,0);if(c<s+o)throw new Error(Ur.INSUFFICIENT_FUNDS(c,s+o));const f=new oe.Psbt({network:r});for(const d of a){const y=await t.getTransactionHex(d.txid);f.addInput({hash:tu(d.txid),index:d.vout,nonWitnessUtxo:Buffer.from(y,"hex")})}const u=c-s-o;return f.addOutput({address:i,value:s}),u>546&&f.addOutput({address:n,value:u}),{txHex:f.toHex(),utxoCount:a.length}}async _send(t,r,n){var f;if(n||(n=await this.provider.suggestFee(await this.getAddress(),r,In.FAST)),n>r)throw new Error(Ur.FEE_EXCEEDS_AMOUNT(n,r));if(r<this.minAmt)throw new Error(Ur.MIN_AMOUNT(this.minAmt));const i=await this.getAddress(),s=await this.provider.getUTXOs(i,r+n),o=s.reduce((u,d)=>u+d.value,0),a=new oe.Psbt({network:this.network});for(const u of s){const d=await this.provider.getTransactionHex(u.txid),y=await this.provider.getTransaction(u.txid);let p;this.pkType===fi["p2wpkh-p2sh"]&&(p={witnessUtxo:{script:Buffer.from(y.vout[u.vout].scriptpubkey,"hex"),value:u.value},redeemScript:(f=oe.payments.p2sh({redeem:oe.payments.p2wpkh({pubkey:this.signer.publicKey,network:this.network}),network:this.network}).redeem)==null?void 0:f.output}),a.addInput({hash:tu(u.txid),index:u.vout,nonWitnessUtxo:Buffer.from(d,"hex"),...p})}const c=o-r-n;return a.addOutput({address:t,value:r}),c>0&&a.addOutput({address:i,value:c}),a.signAllInputs(this.signer).finalizeAllInputs(),a.extractTransaction().toHex()}async send(t,r,n){const i=await this._send(t,r,n);return this.provider.broadcast(i)}async sign(t){return t=t.startsWith("0x")?t.slice(2):t,this.signer.sign(Buffer.from(t,"hex")).toString("hex")}async signSchnorr(t){return this.signer.signSchnorr(t)}}const Vx="2bag6xpshpvPe7SJ9nSDLHpxqhEAoHPGpEkjNSv7gxoF",Wx={name:"solana_native_swaps",version:"0.3.0",spec:"0.1.0",description:"Created with Anchor"},Kx=[{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:[]}],Yx=[{name:"SwapAccount",discriminator:[53,126,9,14,14,197,105,182]}],Zx=[{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]}],Xx=[{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"}],Jx=[{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]}}]}}],au={address:Vx,metadata:Wx,instructions:Kx,accounts:Yx,events:Zx,errors:Xx,types:Jx};var sr={},jn={};Object.defineProperty(jn,"__esModule",{value:!0});jn.decode=jn.encode=void 0;const Vd=un;function Qx(e){return e.reduce((t,r)=>t+r.toString(16).padStart(2,"0"),"0x")}jn.encode=Qx;function eA(e){e.indexOf("0x")===0&&(e=e.substr(2)),e.length%2===1&&(e="0"+e);let t=e.match(/.{2}/g);return t===null?Vd.Buffer.from([]):Vd.Buffer.from(t.map(r=>parseInt(r,16)))}jn.decode=eA;var zn={},Br={},ga;Object.defineProperty(Br,"__esModule",{value:!0});Br.isVersionedTransaction=Br.chunks=Br.isBrowser=void 0;Br.isBrowser=process.env.ANCHOR_BROWSER||typeof window<"u"&&!(!((ga=window.process)===null||ga===void 0)&&ga.hasOwnProperty("type"));function tA(e,t){return Array.apply(0,new Array(Math.ceil(e.length/t))).map((r,n)=>e.slice(n*t,(n+1)*t))}Br.chunks=tA;const rA=e=>"version"in e;Br.isVersionedTransaction=rA;var ba={},wa={},va,Wd;function Sy(){return Wd||(Wd=1,va=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var t={},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 i=42;t[r]=i;for(var s in t)return!1;if(typeof Object.keys=="function"&&Object.keys(t).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(t).length!==0)return!1;var o=Object.getOwnPropertySymbols(t);if(o.length!==1||o[0]!==r||!Object.prototype.propertyIsEnumerable.call(t,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var a=Object.getOwnPropertyDescriptor(t,r);if(a.value!==i||a.enumerable!==!0)return!1}return!0}),va}var Ea,Kd;function Fo(){if(Kd)return Ea;Kd=1;var e=Sy();return Ea=function(){return e()&&!!Symbol.toStringTag},Ea}var xa,Yd;function Py(){return Yd||(Yd=1,xa=Object),xa}var Aa,Zd;function nA(){return Zd||(Zd=1,Aa=Error),Aa}var _a,Xd;function iA(){return Xd||(Xd=1,_a=EvalError),_a}var Sa,Jd;function sA(){return Jd||(Jd=1,Sa=RangeError),Sa}var Pa,Qd;function oA(){return Qd||(Qd=1,Pa=ReferenceError),Pa}var Ta,el;function Ty(){return el||(el=1,Ta=SyntaxError),Ta}var Ia,tl;function ls(){return tl||(tl=1,Ia=TypeError),Ia}var ka,rl;function aA(){return rl||(rl=1,ka=URIError),ka}var Ba,nl;function cA(){return nl||(nl=1,Ba=Math.abs),Ba}var Oa,il;function uA(){return il||(il=1,Oa=Math.floor),Oa}var Ca,sl;function fA(){return sl||(sl=1,Ca=Math.max),Ca}var Ra,ol;function dA(){return ol||(ol=1,Ra=Math.min),Ra}var Na,al;function lA(){return al||(al=1,Na=Math.pow),Na}var Fa,cl;function pA(){return cl||(cl=1,Fa=Math.round),Fa}var $a,ul;function hA(){return ul||(ul=1,$a=Number.isNaN||function(t){return t!==t}),$a}var Ua,fl;function yA(){if(fl)return Ua;fl=1;var e=hA();return Ua=function(r){return e(r)||r===0?r:r<0?-1:1},Ua}var Ha,dl;function mA(){return dl||(dl=1,Ha=Object.getOwnPropertyDescriptor),Ha}var La,ll;function Qn(){if(ll)return La;ll=1;var e=mA();if(e)try{e([],"length")}catch{e=null}return La=e,La}var Ma,pl;function $o(){if(pl)return Ma;pl=1;var e=Object.defineProperty||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Ma=e,Ma}var Da,hl;function gA(){if(hl)return Da;hl=1;var e=typeof Symbol<"u"&&Symbol,t=Sy();return Da=function(){return typeof e!="function"||typeof Symbol!="function"||typeof e("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:t()},Da}var ja,yl;function Iy(){return yl||(yl=1,ja=typeof Reflect<"u"&&Reflect.getPrototypeOf||null),ja}var za,ml;function ky(){if(ml)return za;ml=1;var e=Py();return za=e.getPrototypeOf||null,za}var qa,gl;function bA(){if(gl)return qa;gl=1;var e="Function.prototype.bind called on incompatible ",t=Object.prototype.toString,r=Math.max,n="[object Function]",i=function(c,f){for(var u=[],d=0;d<c.length;d+=1)u[d]=c[d];for(var y=0;y<f.length;y+=1)u[y+c.length]=f[y];return u},s=function(c,f){for(var u=[],d=f,y=0;d<c.length;d+=1,y+=1)u[y]=c[d];return u},o=function(a,c){for(var f="",u=0;u<a.length;u+=1)f+=a[u],u+1<a.length&&(f+=c);return f};return qa=function(c){var f=this;if(typeof f!="function"||t.apply(f)!==n)throw new TypeError(e+f);for(var u=s(arguments,1),d,y=function(){if(this instanceof d){var A=f.apply(this,i(u,arguments));return Object(A)===A?A:this}return f.apply(c,i(u,arguments))},p=r(0,f.length-u.length),g=[],b=0;b<p;b++)g[b]="$"+b;if(d=Function("binder","return function ("+o(g,",")+"){ return binder.apply(this,arguments); }")(y),f.prototype){var E=function(){};E.prototype=f.prototype,d.prototype=new E,E.prototype=null}return d},qa}var Ga,bl;function ps(){if(bl)return Ga;bl=1;var e=bA();return Ga=Function.prototype.bind||e,Ga}var Va,wl;function yf(){return wl||(wl=1,Va=Function.prototype.call),Va}var Wa,vl;function mf(){return vl||(vl=1,Wa=Function.prototype.apply),Wa}var Ka,El;function wA(){return El||(El=1,Ka=typeof Reflect<"u"&&Reflect&&Reflect.apply),Ka}var Ya,xl;function By(){if(xl)return Ya;xl=1;var e=ps(),t=mf(),r=yf(),n=wA();return Ya=n||e.call(r,t),Ya}var Za,Al;function gf(){if(Al)return Za;Al=1;var e=ps(),t=ls(),r=yf(),n=By();return Za=function(s){if(s.length<1||typeof s[0]!="function")throw new t("a function is required");return n(e,r,s)},Za}var Xa,_l;function vA(){if(_l)return Xa;_l=1;var e=gf(),t=Qn(),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&&t&&t(Object.prototype,"__proto__"),i=Object,s=i.getPrototypeOf;return Xa=n&&typeof n.get=="function"?e([n.get]):typeof s=="function"?function(a){return s(a==null?a:i(a))}:!1,Xa}var Ja,Sl;function bf(){if(Sl)return Ja;Sl=1;var e=Iy(),t=ky(),r=vA();return Ja=e?function(i){return e(i)}:t?function(i){if(!i||typeof i!="object"&&typeof i!="function")throw new TypeError("getProto: not an object");return t(i)}:r?function(i){return r(i)}:null,Ja}var Qa,Pl;function Oy(){if(Pl)return Qa;Pl=1;var e=Function.prototype.call,t=Object.prototype.hasOwnProperty,r=ps();return Qa=r.call(e,t),Qa}var ec,Tl;function Cy(){if(Tl)return ec;Tl=1;var e,t=Py(),r=nA(),n=iA(),i=sA(),s=oA(),o=Ty(),a=ls(),c=aA(),f=cA(),u=uA(),d=fA(),y=dA(),p=lA(),g=pA(),b=yA(),E=Function,A=function(re){try{return E('"use strict"; return ('+re+").constructor;")()}catch{}},P=Qn(),w=$o(),_=function(){throw new a},T=P?function(){try{return arguments.callee,_}catch{try{return P(arguments,"callee").get}catch{return _}}}():_,I=gA()(),R=bf(),L=ky(),S=Iy(),$=mf(),C=yf(),U={},j=typeof Uint8Array>"u"||!R?e:R(Uint8Array),V={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?e:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?e:ArrayBuffer,"%ArrayIteratorPrototype%":I&&R?R([][Symbol.iterator]()):e,"%AsyncFromSyncIteratorPrototype%":e,"%AsyncFunction%":U,"%AsyncGenerator%":U,"%AsyncGeneratorFunction%":U,"%AsyncIteratorPrototype%":U,"%Atomics%":typeof Atomics>"u"?e:Atomics,"%BigInt%":typeof BigInt>"u"?e:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?e:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?e:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?e:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":r,"%eval%":eval,"%EvalError%":n,"%Float16Array%":typeof Float16Array>"u"?e:Float16Array,"%Float32Array%":typeof Float32Array>"u"?e:Float32Array,"%Float64Array%":typeof Float64Array>"u"?e:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?e:FinalizationRegistry,"%Function%":E,"%GeneratorFunction%":U,"%Int8Array%":typeof Int8Array>"u"?e:Int8Array,"%Int16Array%":typeof Int16Array>"u"?e:Int16Array,"%Int32Array%":typeof Int32Array>"u"?e:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":I&&R?R(R([][Symbol.iterator]())):e,"%JSON%":typeof JSON=="object"?JSON:e,"%Map%":typeof Map>"u"?e:Map,"%MapIteratorPrototype%":typeof Map>"u"||!I||!R?e:R(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":t,"%Object.getOwnPropertyDescriptor%":P,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?e:Promise,"%Proxy%":typeof Proxy>"u"?e:Proxy,"%RangeError%":i,"%ReferenceError%":s,"%Reflect%":typeof Reflect>"u"?e:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?e:Set,"%SetIteratorPrototype%":typeof Set>"u"||!I||!R?e:R(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?e:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":I&&R?R(""[Symbol.iterator]()):e,"%Symbol%":I?Symbol:e,"%SyntaxError%":o,"%ThrowTypeError%":T,"%TypedArray%":j,"%TypeError%":a,"%Uint8Array%":typeof Uint8Array>"u"?e:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?e:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?e:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?e:Uint32Array,"%URIError%":c,"%WeakMap%":typeof WeakMap>"u"?e:WeakMap,"%WeakRef%":typeof WeakRef>"u"?e:WeakRef,"%WeakSet%":typeof WeakSet>"u"?e:WeakSet,"%Function.prototype.call%":C,"%Function.prototype.apply%":$,"%Object.defineProperty%":w,"%Object.getPrototypeOf%":L,"%Math.abs%":f,"%Math.floor%":u,"%Math.max%":d,"%Math.min%":y,"%Math.pow%":p,"%Math.round%":g,"%Math.sign%":b,"%Reflect.getPrototypeOf%":S};if(R)try{null.error}catch(re){var Y=R(R(re));V["%Error.prototype%"]=Y}var X=function re(te){var se;if(te==="%AsyncFunction%")se=A("async function () {}");else if(te==="%GeneratorFunction%")se=A("function* () {}");else if(te==="%AsyncGeneratorFunction%")se=A("async function* () {}");else if(te==="%AsyncGenerator%"){var de=re("%AsyncGeneratorFunction%");de&&(se=de.prototype)}else if(te==="%AsyncIteratorPrototype%"){var he=re("%AsyncGenerator%");he&&R&&(se=R(he.prototype))}return V[te]=se,se},J={__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"]},M=ps(),B=Oy(),q=M.call(C,Array.prototype.concat),W=M.call($,Array.prototype.splice),k=M.call(C,String.prototype.replace),N=M.call(C,String.prototype.slice),H=M.call(C,RegExp.prototype.exec),Z=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,Q=/\\(\\)?/g,ie=function(te){var se=N(te,0,1),de=N(te,-1);if(se==="%"&&de!=="%")throw new o("invalid intrinsic syntax, expected closing `%`");if(de==="%"&&se!=="%")throw new o("invalid intrinsic syntax, expected opening `%`");var he=[];return k(te,Z,function(Ae,at,Re,Rt){he[he.length]=Re?k(Rt,Q,"$1"):at||Ae}),he},ne=function(te,se){var de=te,he;if(B(J,de)&&(he=J[de],de="%"+he[0]+"%"),B(V,de)){var Ae=V[de];if(Ae===U&&(Ae=X(de)),typeof Ae>"u"&&!se)throw new a("intrinsic "+te+" exists, but is not available. Please file an issue!");return{alias:he,name:de,value:Ae}}throw new o("intrinsic "+te+" does not exist!")};return ec=function(te,se){if(typeof te!="string"||te.length===0)throw new a("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof se!="boolean")throw new a('"allowMissing" argument must be a boolean');if(H(/^%?[^%]*%?$/,te)===null)throw new o("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var de=ie(te),he=de.length>0?de[0]:"",Ae=ne("%"+he+"%",se),at=Ae.name,Re=Ae.value,Rt=!1,Fr=Ae.alias;Fr&&(he=Fr[0],W(de,q([0,1],Fr)));for(var G=1,Nt=!0;G<de.length;G+=1){var Ge=de[G],Ve=N(Ge,0,1),hr=N(Ge,-1);if((Ve==='"'||Ve==="'"||Ve==="`"||hr==='"'||hr==="'"||hr==="`")&&Ve!==hr)throw new o("property names with quotes must have matching quotes");if((Ge==="constructor"||!Nt)&&(Rt=!0),he+="."+Ge,at="%"+he+"%",B(V,at))Re=V[at];else if(Re!=null){if(!(Ge in Re)){if(!se)throw new a("base intrinsic for "+te+" exists, but the property is not available.");return}if(P&&G+1>=de.length){var ln=P(Re,Ge);Nt=!!ln,Nt&&"get"in ln&&!("originalValue"in ln.get)?Re=ln.get:Re=Re[Ge]}else Nt=B(Re,Ge),Re=Re[Ge];Nt&&!Rt&&(V[at]=Re)}}return Re},ec}var tc,Il;function hs(){if(Il)return tc;Il=1;var e=Cy(),t=gf(),r=t([e("%String.prototype.indexOf%")]);return tc=function(i,s){var o=e(i,!!s);return typeof o=="function"&&r(i,".prototype.")>-1?t([o]):o},tc}var rc,kl;function EA(){if(kl)return rc;kl=1;var e=Fo()(),t=hs(),r=t("Object.prototype.toString"),n=function(a){return e&&a&&typeof a=="object"&&Symbol.toStringTag in a?!1:r(a)==="[object Arguments]"},i=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]"},s=function(){return n(arguments)}();return n.isLegacyArguments=i,rc=s?n:i,rc}var nc,Bl;function xA(){if(Bl)return nc;Bl=1;var e=hs(),t=Fo()(),r=Oy(),n=Qn(),i;if(t){var s=e("RegExp.prototype.exec"),o={},a=function(){throw o},c={toString:a,valueOf:a};typeof Symbol.toPrimitive=="symbol"&&(c[Symbol.toPrimitive]=a),i=function(y){if(!y||typeof y!="object")return!1;var p=n(y,"lastIndex"),g=p&&r(p,"value");if(!g)return!1;try{s(y,c)}catch(b){return b===o}}}else{var f=e("Object.prototype.toString"),u="[object RegExp]";i=function(y){return!y||typeof y!="object"&&typeof y!="function"?!1:f(y)===u}}return nc=i,nc}var ic,Ol;function AA(){if(Ol)return ic;Ol=1;var e=hs(),t=xA(),r=e("RegExp.prototype.exec"),n=ls();return ic=function(s){if(!t(s))throw new n("`regex` must be a RegExp");return function(a){return r(s,a)!==null}},ic}var sc,Cl;function _A(){if(Cl)return sc;Cl=1;var e=hs(),t=AA(),r=t(/^\s*(?:function)?\*/),n=Fo()(),i=bf(),s=e("Object.prototype.toString"),o=e("Function.prototype.toString"),a=function(){if(!n)return!1;try{return Function("return function*() {}")()}catch{}},c;return sc=function(u){if(typeof u!="function")return!1;if(r(o(u)))return!0;if(!n){var d=s(u);return d==="[object GeneratorFunction]"}if(!i)return!1;if(typeof c>"u"){var y=a();c=y?i(y):!1}return i(u)===c},sc}var oc,Rl;function SA(){if(Rl)return oc;Rl=1;var e=Function.prototype.toString,t=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,r,n;if(typeof t=="function"&&typeof Object.defineProperty=="function")try{r=Object.defineProperty({},"length",{get:function(){throw n}}),n={},t(function(){throw 42},null,r)}catch(P){P!==n&&(t=null)}else t=null;var i=/^\s*class\b/,s=function(w){try{var _=e.call(w);return i.test(_)}catch{return!1}},o=function(w){try{return s(w)?!1:(e.call(w),!0)}catch{return!1}},a=Object.prototype.toString,c="[object Object]",f="[object Function]",u="[object GeneratorFunction]",d="[object HTMLAllCollection]",y="[object HTML document.all class]",p="[object HTMLCollection]",g=typeof Symbol=="function"&&!!Symbol.toStringTag,b=!(0 in[,]),E=function(){return!1};if(typeof document=="object"){var A=document.all;a.call(A)===a.call(document.all)&&(E=function(w){if((b||!w)&&(typeof w>"u"||typeof w=="object"))try{var _=a.call(w);return(_===d||_===y||_===p||_===c)&&w("")==null}catch{}return!1})}return oc=t?function(w){if(E(w))return!0;if(!w||typeof w!="function"&&typeof w!="object")return!1;try{t(w,null,r)}catch(_){if(_!==n)return!1}return!s(w)&&o(w)}:function(w){if(E(w))return!0;if(!w||typeof w!="function"&&typeof w!="object")return!1;if(g)return o(w);if(s(w))return!1;var _=a.call(w);return _!==f&&_!==u&&!/^\[object HTML/.test(_)?!1:o(w)},oc}var ac,Nl;function PA(){if(Nl)return ac;Nl=1;var e=SA(),t=Object.prototype.toString,r=Object.prototype.hasOwnProperty,n=function(c,f,u){for(var d=0,y=c.length;d<y;d++)r.call(c,d)&&(u==null?f(c[d],d,c):f.call(u,c[d],d,c))},i=function(c,f,u){for(var d=0,y=c.length;d<y;d++)u==null?f(c.charAt(d),d,c):f.call(u,c.charAt(d),d,c)},s=function(c,f,u){for(var d in c)r.call(c,d)&&(u==null?f(c[d],d,c):f.call(u,c[d],d,c))};function o(a){return t.call(a)==="[object Array]"}return ac=function(c,f,u){if(!e(f))throw new TypeError("iterator must be a function");var d;arguments.length>=3&&(d=u),o(c)?n(c,f,d):typeof c=="string"?i(c,f,d):s(c,f,d)},ac}var cc,Fl;function TA(){return Fl||(Fl=1,cc=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]),cc}var uc,$l;function IA(){if($l)return uc;$l=1;var e=TA(),t=typeof globalThis>"u"?Kt:globalThis;return uc=function(){for(var n=[],i=0;i<e.length;i++)typeof t[e[i]]=="function"&&(n[n.length]=e[i]);return n},uc}var fc={exports:{}},dc,Ul;function kA(){if(Ul)return dc;Ul=1;var e=$o(),t=Ty(),r=ls(),n=Qn();return dc=function(s,o,a){if(!s||typeof s!="object"&&typeof s!="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,f=arguments.length>4?arguments[4]:null,u=arguments.length>5?arguments[5]:null,d=arguments.length>6?arguments[6]:!1,y=!!n&&n(s,o);if(e)e(s,o,{configurable:u===null&&y?y.configurable:!u,enumerable:c===null&&y?y.enumerable:!c,value:a,writable:f===null&&y?y.writable:!f});else if(d||!c&&!f&&!u)s[o]=a;else throw new t("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},dc}var lc,Hl;function BA(){if(Hl)return lc;Hl=1;var e=$o(),t=function(){return!!e};return t.hasArrayLengthDefineBug=function(){if(!e)return null;try{return e([],"length",{value:1}).length!==1}catch{return!0}},lc=t,lc}var pc,Ll;function OA(){if(Ll)return pc;Ll=1;var e=Cy(),t=kA(),r=BA()(),n=Qn(),i=ls(),s=e("%Math.floor%");return pc=function(a,c){if(typeof a!="function")throw new i("`fn` is not a function");if(typeof c!="number"||c<0||c>4294967295||s(c)!==c)throw new i("`length` must be a positive 32-bit integer");var f=arguments.length>2&&!!arguments[2],u=!0,d=!0;if("length"in a&&n){var y=n(a,"length");y&&!y.configurable&&(u=!1),y&&!y.writable&&(d=!1)}return(u||d||!f)&&(r?t(a,"length",c,!0,!0):t(a,"length",c)),a},pc}var hc,Ml;function CA(){if(Ml)return hc;Ml=1;var e=ps(),t=mf(),r=By();return hc=function(){return r(e,t,arguments)},hc}var Dl;function RA(){return Dl||(Dl=1,function(e){var t=OA(),r=$o(),n=gf(),i=CA();e.exports=function(o){var a=n(arguments),c=o.length-(arguments.length-1);return t(a,1+(c>0?c:0),!0)},r?r(e.exports,"apply",{value:i}):e.exports.apply=i}(fc)),fc.exports}var yc,jl;function Ry(){if(jl)return yc;jl=1;var e=PA(),t=IA(),r=RA(),n=hs(),i=Qn(),s=bf(),o=n("Object.prototype.toString"),a=Fo()(),c=typeof globalThis>"u"?Kt:globalThis,f=t(),u=n("String.prototype.slice"),d=n("Array.prototype.indexOf",!0)||function(E,A){for(var P=0;P<E.length;P+=1)if(E[P]===A)return P;return-1},y={__proto__:null};a&&i&&s?e(f,function(b){var E=new c[b];if(Symbol.toStringTag in E&&s){var A=s(E),P=i(A,Symbol.toStringTag);if(!P&&A){var w=s(A);P=i(w,Symbol.toStringTag)}y["$"+b]=r(P.get)}}):e(f,function(b){var E=new c[b],A=E.slice||E.set;A&&(y["$"+b]=r(A))});var p=function(E){var A=!1;return e(y,function(P,w){if(!A)try{"$"+P(E)===w&&(A=u(w,1))}catch{}}),A},g=function(E){var A=!1;return e(y,function(P,w){if(!A)try{P(E),A=u(w,1)}catch{}}),A};return yc=function(E){if(!E||typeof E!="object")return!1;if(!a){var A=u(o(E),8,-1);return d(f,A)>-1?A:A!=="Object"?!1:g(E)}return i?p(E):null},yc}var mc,zl;function NA(){if(zl)return mc;zl=1;var e=Ry();return mc=function(r){return!!e(r)},mc}var ql;function FA(){return ql||(ql=1,function(e){var t=EA(),r=_A(),n=Ry(),i=NA();function s(G){return G.call.bind(G)}var o=typeof BigInt<"u",a=typeof Symbol<"u",c=s(Object.prototype.toString),f=s(Number.prototype.valueOf),u=s(String.prototype.valueOf),d=s(Boolean.prototype.valueOf);if(o)var y=s(BigInt.prototype.valueOf);if(a)var p=s(Symbol.prototype.valueOf);function g(G,Nt){if(typeof G!="object")return!1;try{return Nt(G),!0}catch{return!1}}e.isArgumentsObject=t,e.isGeneratorFunction=r,e.isTypedArray=i;function b(G){return typeof Promise<"u"&&G instanceof Promise||G!==null&&typeof G=="object"&&typeof G.then=="function"&&typeof G.catch=="function"}e.isPromise=b;function E(G){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(G):i(G)||N(G)}e.isArrayBufferView=E;function A(G){return n(G)==="Uint8Array"}e.isUint8Array=A;function P(G){return n(G)==="Uint8ClampedArray"}e.isUint8ClampedArray=P;function w(G){return n(G)==="Uint16Array"}e.isUint16Array=w;function _(G){return n(G)==="Uint32Array"}e.isUint32Array=_;function T(G){return n(G)==="Int8Array"}e.isInt8Array=T;function I(G){return n(G)==="Int16Array"}e.isInt16Array=I;function R(G){return n(G)==="Int32Array"}e.isInt32Array=R;function L(G){return n(G)==="Float32Array"}e.isFloat32Array=L;function S(G){return n(G)==="Float64Array"}e.isFloat64Array=S;function $(G){return n(G)==="BigInt64Array"}e.isBigInt64Array=$;function C(G){return n(G)==="BigUint64Array"}e.isBigUint64Array=C;function U(G){return c(G)==="[object Map]"}U.working=typeof Map<"u"&&U(new Map);function j(G){return typeof Map>"u"?!1:U.working?U(G):G instanceof Map}e.isMap=j;function V(G){return c(G)==="[object Set]"}V.working=typeof Set<"u"&&V(new Set);function Y(G){return typeof Set>"u"?!1:V.working?V(G):G instanceof Set}e.isSet=Y;function X(G){return c(G)==="[object WeakMap]"}X.working=typeof WeakMap<"u"&&X(new WeakMap);function J(G){return typeof WeakMap>"u"?!1:X.working?X(G):G instanceof WeakMap}e.isWeakMap=J;function M(G){return c(G)==="[object WeakSet]"}M.working=typeof WeakSet<"u"&&M(new WeakSet);function B(G){return M(G)}e.isWeakSet=B;function q(G){return c(G)==="[object ArrayBuffer]"}q.working=typeof ArrayBuffer<"u"&&q(new ArrayBuffer);function W(G){return typeof ArrayBuffer>"u"?!1:q.working?q(G):G instanceof ArrayBuffer}e.isArrayBuffer=W;function k(G){return c(G)==="[object DataView]"}k.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&k(new DataView(new ArrayBuffer(1),0,1));function N(G){return typeof DataView>"u"?!1:k.working?k(G):G instanceof DataView}e.isDataView=N;var H=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function Z(G){return c(G)==="[object SharedArrayBuffer]"}function Q(G){return typeof H>"u"?!1:(typeof Z.working>"u"&&(Z.working=Z(new H)),Z.working?Z(G):G instanceof H)}e.isSharedArrayBuffer=Q;function ie(G){return c(G)==="[object AsyncFunction]"}e.isAsyncFunction=ie;function ne(G){return c(G)==="[object Map Iterator]"}e.isMapIterator=ne;function re(G){return c(G)==="[object Set Iterator]"}e.isSetIterator=re;function te(G){return c(G)==="[object Generator]"}e.isGeneratorObject=te;function se(G){return c(G)==="[object WebAssembly.Module]"}e.isWebAssemblyCompiledModule=se;function de(G){return g(G,f)}e.isNumberObject=de;function he(G){return g(G,u)}e.isStringObject=he;function Ae(G){return g(G,d)}e.isBooleanObject=Ae;function at(G){return o&&g(G,y)}e.isBigIntObject=at;function Re(G){return a&&g(G,p)}e.isSymbolObject=Re;function Rt(G){return de(G)||he(G)||Ae(G)||at(G)||Re(G)}e.isBoxedPrimitive=Rt;function Fr(G){return typeof Uint8Array<"u"&&(W(G)||Q(G))}e.isAnyArrayBuffer=Fr,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(G){Object.defineProperty(e,G,{enumerable:!1,value:function(){throw new Error(G+" is not supported in userland")}})})}(wa)),wa}var gc,Gl;function $A(){return Gl||(Gl=1,gc=function(t){return t&&typeof t=="object"&&typeof t.copy=="function"&&typeof t.fill=="function"&&typeof t.readUInt8=="function"}),gc}var Rs={exports:{}},Vl;function UA(){return Vl||(Vl=1,typeof Object.create=="function"?Rs.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:Rs.exports=function(t,r){if(r){t.super_=r;var n=function(){};n.prototype=r.prototype,t.prototype=new n,t.prototype.constructor=t}}),Rs.exports}var Wl;function Ny(){return Wl||(Wl=1,function(e){var t=Object.getOwnPropertyDescriptors||function(N){for(var H=Object.keys(N),Z={},Q=0;Q<H.length;Q++)Z[H[Q]]=Object.getOwnPropertyDescriptor(N,H[Q]);return Z},r=/%[sdj%]/g;e.format=function(k){if(!T(k)){for(var N=[],H=0;H<arguments.length;H++)N.push(o(arguments[H]));return N.join(" ")}for(var H=1,Z=arguments,Q=Z.length,ie=String(k).replace(r,function(re){if(re==="%%")return"%";if(H>=Q)return re;switch(re){case"%s":return String(Z[H++]);case"%d":return Number(Z[H++]);case"%j":try{return JSON.stringify(Z[H++])}catch{return"[Circular]"}default:return re}}),ne=Z[H];H<Q;ne=Z[++H])P(ne)||!S(ne)?ie+=" "+ne:ie+=" "+o(ne);return ie},e.deprecate=function(k,N){if(typeof process<"u"&&process.noDeprecation===!0)return k;if(typeof process>"u")return function(){return e.deprecate(k,N).apply(this,arguments)};var H=!1;function Z(){if(!H){if(process.throwDeprecation)throw new Error(N);process.traceDeprecation?console.trace(N):console.error(N),H=!0}return k.apply(this,arguments)}return Z};var n={},i=/^$/;if(process.env.NODE_DEBUG){var s=process.env.NODE_DEBUG;s=s.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),i=new RegExp("^"+s+"$","i")}e.debuglog=function(k){if(k=k.toUpperCase(),!n[k])if(i.test(k)){var N=process.pid;n[k]=function(){var H=e.format.apply(e,arguments);console.error("%s %d: %s",k,N,H)}}else n[k]=function(){};return n[k]};function o(k,N){var H={seen:[],stylize:c};return arguments.length>=3&&(H.depth=arguments[2]),arguments.length>=4&&(H.colors=arguments[3]),A(N)?H.showHidden=N:N&&e._extend(H,N),R(H.showHidden)&&(H.showHidden=!1),R(H.depth)&&(H.depth=2),R(H.colors)&&(H.colors=!1),R(H.customInspect)&&(H.customInspect=!0),H.colors&&(H.stylize=a),u(H,k,H.depth)}e.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(k,N){var H=o.styles[N];return H?"\x1B["+o.colors[H][0]+"m"+k+"\x1B["+o.colors[H][1]+"m":k}function c(k,N){return k}function f(k){var N={};return k.forEach(function(H,Z){N[H]=!0}),N}function u(k,N,H){if(k.customInspect&&N&&U(N.inspect)&&N.inspect!==e.inspect&&!(N.constructor&&N.constructor.prototype===N)){var Z=N.inspect(H,k);return T(Z)||(Z=u(k,Z,H)),Z}var Q=d(k,N);if(Q)return Q;var ie=Object.keys(N),ne=f(ie);if(k.showHidden&&(ie=Object.getOwnPropertyNames(N)),C(N)&&(ie.indexOf("message")>=0||ie.indexOf("description")>=0))return y(N);if(ie.length===0){if(U(N)){var re=N.name?": "+N.name:"";return k.stylize("[Function"+re+"]","special")}if(L(N))return k.stylize(RegExp.prototype.toString.call(N),"regexp");if($(N))return k.stylize(Date.prototype.toString.call(N),"date");if(C(N))return y(N)}var te="",se=!1,de=["{","}"];if(E(N)&&(se=!0,de=["[","]"]),U(N)){var he=N.name?": "+N.name:"";te=" [Function"+he+"]"}if(L(N)&&(te=" "+RegExp.prototype.toString.call(N)),$(N)&&(te=" "+Date.prototype.toUTCString.call(N)),C(N)&&(te=" "+y(N)),ie.length===0&&(!se||N.length==0))return de[0]+te+de[1];if(H<0)return L(N)?k.stylize(RegExp.prototype.toString.call(N),"regexp"):k.stylize("[Object]","special");k.seen.push(N);var Ae;return se?Ae=p(k,N,H,ne,ie):Ae=ie.map(function(at){return g(k,N,H,ne,at,se)}),k.seen.pop(),b(Ae,te,de)}function d(k,N){if(R(N))return k.stylize("undefined","undefined");if(T(N)){var H="'"+JSON.stringify(N).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return k.stylize(H,"string")}if(_(N))return k.stylize(""+N,"number");if(A(N))return k.stylize(""+N,"boolean");if(P(N))return k.stylize("null","null")}function y(k){return"["+Error.prototype.toString.call(k)+"]"}function p(k,N,H,Z,Q){for(var ie=[],ne=0,re=N.length;ne<re;++ne)M(N,String(ne))?ie.push(g(k,N,H,Z,String(ne),!0)):ie.push("");return Q.forEach(function(te){te.match(/^\d+$/)||ie.push(g(k,N,H,Z,te,!0))}),ie}function g(k,N,H,Z,Q,ie){var ne,re,te;if(te=Object.getOwnPropertyDescriptor(N,Q)||{value:N[Q]},te.get?te.set?re=k.stylize("[Getter/Setter]","special"):re=k.stylize("[Getter]","special"):te.set&&(re=k.stylize("[Setter]","special")),M(Z,Q)||(ne="["+Q+"]"),re||(k.seen.indexOf(te.value)<0?(P(H)?re=u(k,te.value,null):re=u(k,te.value,H-1),re.indexOf(`
91
91
  `)>-1&&(ie?re=re.split(`
92
92
  `).map(function(se){return" "+se}).join(`
93
93
  `).slice(2):re=`
@@ -96,4 +96,4 @@ ${tb(p)}`),super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessa
96
96
  `))):re=k.stylize("[Circular]","special")),R(ne)){if(ie&&Q.match(/^\d+$/))return re;ne=JSON.stringify(""+Q),ne.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(ne=ne.slice(1,-1),ne=k.stylize(ne,"name")):(ne=ne.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),ne=k.stylize(ne,"string"))}return ne+": "+re}function b(k,N,H){var Z=k.reduce(function(Q,ie){return ie.indexOf(`
97
97
  `)>=0,Q+ie.replace(/\u001b\[\d\d?m/g,"").length+1},0);return Z>60?H[0]+(N===""?"":N+`
98
98
  `)+" "+k.join(`,
99
- `)+" "+H[1]:H[0]+N+" "+k.join(", ")+" "+H[1]}e.types=RA();function E(k){return Array.isArray(k)}e.isArray=E;function A(k){return typeof k=="boolean"}e.isBoolean=A;function P(k){return k===null}e.isNull=P;function w(k){return k==null}e.isNullOrUndefined=w;function _(k){return typeof k=="number"}e.isNumber=_;function T(k){return typeof k=="string"}e.isString=T;function I(k){return typeof k=="symbol"}e.isSymbol=I;function R(k){return k===void 0}e.isUndefined=R;function L(k){return S(k)&&V(k)==="[object RegExp]"}e.isRegExp=L,e.types.isRegExp=L;function S(k){return typeof k=="object"&&k!==null}e.isObject=S;function $(k){return S(k)&&V(k)==="[object Date]"}e.isDate=$,e.types.isDate=$;function C(k){return S(k)&&(V(k)==="[object Error]"||k instanceof Error)}e.isError=C,e.types.isNativeError=C;function U(k){return typeof k=="function"}e.isFunction=U;function j(k){return k===null||typeof k=="boolean"||typeof k=="number"||typeof k=="string"||typeof k=="symbol"||typeof k>"u"}e.isPrimitive=j,e.isBuffer=NA();function V(k){return Object.prototype.toString.call(k)}function Y(k){return k<10?"0"+k.toString(10):k.toString(10)}var X=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function J(){var k=new Date,N=[Y(k.getHours()),Y(k.getMinutes()),Y(k.getSeconds())].join(":");return[k.getDate(),X[k.getMonth()],N].join(" ")}e.log=function(){console.log("%s - %s",J(),e.format.apply(e,arguments))},e.inherits=FA(),e._extend=function(k,N){if(!N||!S(N))return k;for(var H=Object.keys(N),Z=H.length;Z--;)k[H[Z]]=N[H[Z]];return k};function M(k,N){return Object.prototype.hasOwnProperty.call(k,N)}var B=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;e.promisify=function(N){if(typeof N!="function")throw new TypeError('The "original" argument must be of type Function');if(B&&N[B]){var H=N[B];if(typeof H!="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(H,B,{value:H,enumerable:!1,writable:!1,configurable:!0}),H}function H(){for(var Z,Q,ie=new Promise(function(te,se){Z=te,Q=se}),ne=[],re=0;re<arguments.length;re++)ne.push(arguments[re]);ne.push(function(te,se){te?Q(te):Z(se)});try{N.apply(this,ne)}catch(te){Q(te)}return ie}return Object.setPrototypeOf(H,Object.getPrototypeOf(N)),B&&Object.defineProperty(H,B,{value:H,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(H,t(N))},e.promisify.custom=B;function q(k,N){if(!k){var H=new Error("Promise was rejected with a falsy value");H.reason=k,k=H}return N(k)}function W(k){if(typeof k!="function")throw new TypeError('The "original" argument must be of type Function');function N(){for(var H=[],Z=0;Z<arguments.length;Z++)H.push(arguments[Z]);var Q=H.pop();if(typeof Q!="function")throw new TypeError("The last argument must be of type Function");var ie=this,ne=function(){return Q.apply(ie,arguments)};k.apply(this,H).then(function(re){process.nextTick(ne.bind(null,null,re))},function(re){process.nextTick(q.bind(null,re,ne))})}return Object.setPrototypeOf(N,Object.getPrototypeOf(k)),Object.defineProperties(N,t(k)),N}e.callbackify=W}(ba)),ba}Object.defineProperty(zn,"__esModule",{value:!0});zn.encode=zn.decode=void 0;const Fy=Br;function $A(e){return(Fy.isBrowser?new TextDecoder("utf-8"):new(Ny()).TextDecoder("utf-8")).decode(e)}zn.decode=$A;function UA(e){return(Fy.isBrowser?new TextEncoder:new(Ny()).TextEncoder("utf-8")).encode(e)}zn.encode=UA;var qn={},cu={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */(function(e,t){var r=un,n=r.Buffer;function i(o,a){for(var c in o)a[c]=o[c]}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=s);function s(o,a,c){return n(o,a,c)}s.prototype=Object.create(n.prototype),i(n,s),s.from=function(o,a,c){if(typeof o=="number")throw new TypeError("Argument must not be a number");return n(o,a,c)},s.alloc=function(o,a,c){if(typeof o!="number")throw new TypeError("Argument must be a number");var f=n(o);return a!==void 0?typeof c=="string"?f.fill(a,c):f.fill(a):f.fill(0),f},s.allocUnsafe=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return n(o)},s.allocUnsafeSlow=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return r.SlowBuffer(o)}})(cu,cu.exports);var HA=cu.exports,Ns=HA.Buffer;function LA(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var n=0;n<e.length;n++){var i=e.charAt(n),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=n}var o=e.length,a=e.charAt(0),c=Math.log(o)/Math.log(256),f=Math.log(256)/Math.log(o);function u(p){if((Array.isArray(p)||p instanceof Uint8Array)&&(p=Ns.from(p)),!Ns.isBuffer(p))throw new TypeError("Expected Buffer");if(p.length===0)return"";for(var g=0,b=0,E=0,A=p.length;E!==A&&p[E]===0;)E++,g++;for(var P=(A-E)*f+1>>>0,w=new Uint8Array(P);E!==A;){for(var _=p[E],T=0,I=P-1;(_!==0||T<b)&&I!==-1;I--,T++)_+=256*w[I]>>>0,w[I]=_%o>>>0,_=_/o>>>0;if(_!==0)throw new Error("Non-zero carry");b=T,E++}for(var R=P-b;R!==P&&w[R]===0;)R++;for(var L=a.repeat(g);R<P;++R)L+=e.charAt(w[R]);return L}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return Ns.alloc(0);for(var g=0,b=0,E=0;p[g]===a;)b++,g++;for(var A=(p.length-g)*c+1>>>0,P=new Uint8Array(A);g<p.length;){var w=p.charCodeAt(g);if(w>255)return;var _=t[w];if(_===255)return;for(var T=0,I=A-1;(_!==0||T<E)&&I!==-1;I--,T++)_+=o*P[I]>>>0,P[I]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");E=T,g++}for(var R=A-E;R!==A&&P[R]===0;)R++;var L=Ns.allocUnsafe(b+(A-R));L.fill(0,0,b);for(var S=b;R!==A;)L[S++]=P[R++];return L}function y(p){var g=d(p);if(g)return g;throw new Error("Non-base"+o+" character")}return{encode:u,decodeUnsafe:d,decode:y}}var MA=LA,DA=MA,jA="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",zA=DA(jA),qA=Kt&&Kt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(qn,"__esModule",{value:!0});qn.decode=qn.encode=void 0;const $y=qA(zA);function GA(e){return $y.default.encode(e)}qn.encode=GA;function VA(e){return $y.default.decode(e)}qn.decode=VA;var Gn={};Object.defineProperty(Gn,"__esModule",{value:!0});Gn.decode=Gn.encode=void 0;const WA=un;function KA(e){return e.toString("base64")}Gn.encode=KA;function YA(e){return WA.Buffer.from(e,"base64")}Gn.decode=YA;var ZA=Kt&&Kt.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),XA=Kt&&Kt.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Uo=Kt&&Kt.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&ZA(t,e,r);return XA(t,e),t};Object.defineProperty(sr,"__esModule",{value:!0});sr.base64=sr.bs58=sr.utf8=Xs=sr.hex=void 0;var Xs=sr.hex=Uo(jn);sr.utf8=Uo(zn);sr.bs58=Uo(qn);sr.base64=Uo(Gn);class Pr{constructor(t,r,n,i,s){try{this.swapId=[...Xs.decode(t)],this.secretHash=[...Xs.decode(n)]}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 Pt.web3.PublicKey(r)}catch(o){throw new Error("Error decoding redeemer. Ensure it is a valid base58 encoded",{cause:o})}try{this.amount=new Pt.BN(i.toString(10),10),this.expiresIn=new Pt.BN(s)}catch(o){throw new Error("Error decoding amount. Invalid value for amount",{cause:o})}if(!(Number.isInteger(s)&&s>0))throw new Error("expiresIn must be a positive integer.")}static from(t){let r;if(t.source_swap.chain.includes("solana"))r=t.source_swap;else if(t.destination_swap.chain.includes("solana"))r=t.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:i,secret_hash:s,timelock:o}=r,a=BigInt(r.amount);return new Pr(n,i,s,a,o)}}function Uy(e){let t;try{t=[...Xs.decode(e)]}catch(r){throw new Error("Error decoding secret. Ensure it is a hex string",{cause:r})}if(t.length!=32)throw new Error("Invalid Secret size. Expected 32 bytes, got "+t.length);return t}class Hy{constructor(t,r,n,i){if(this.provider=t,this.url=r,!t)throw new Error("Provider is required");if(!r)throw new Error("Endpoint URL is required");if(!n)throw new Error("Relayer address is required");if(!i)throw new Error("Program address is required");try{this.relayer=new Pt.web3.PublicKey(n)}catch(o){throw new Error("Error decoding relayer public key. Ensure it is base58 encoded.",{cause:o})}const s={...au,metadata:{...au.metadata??{}},address:i};try{this.program=new Pt.Program(s,this.provider)}catch(o){throw new Error("Error creating Program instance. Ensure the IDL and provider are correct.",{cause:o})}}get htlcActorAddress(){if(!this.program.programId)throw new Error("No program found");return this.provider.publicKey.toBase58()}async sendViaRelayer(t,r){try{t.recentBlockhash=(await this.provider.connection.getLatestBlockhash()).blockhash,t.feePayer=this.relayer;const i=(await this.provider.wallet.signTransaction(t)).serialize({requireAllSignatures:!1}).toString("base64"),s={order_id:r,serialized_tx:i,perform_on:"source"},o=await x.Fetcher.post(this.url.endpoint("/spl-initiate"),{body:JSON.stringify(s),headers:{"Content-Type":"application/json"}});return o.error?x.Err(`Error from Relayer: ${o.error}`):o.result?x.Ok(o.result):x.Err("No result returned from relayer")}catch(n){return x.Err(`Failed to send transaction: ${n instanceof Error?n.message:String(n)}`)}}async initiateViaHTLC(t,r){if(!r)return x.Err("Order is required");try{const n=await this.provider.sendAndConfirm(t);return n?await bd(this.provider.connection,n)?x.Ok(n):x.Err("HTLC: Failed to Initiate swap, confirmation timed out"):x.Err("Failed to initiate HTLC transaction")}catch(n){return x.Err(`Error initiating swap: ${n instanceof Error?n.message:String(n)}`)}}async initiate(t){const{redeemer:r,secretHash:n,amount:i,expiresIn:s}=Pr.from(t),o=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Pt.web3.PublicKey.findProgramAddressSync(o,this.program.programId)[0];try{const a=await this.program.methods.initiate(i,s,r,n).accounts({initiator:this.provider.publicKey}).transaction();return le.isSolanaNativeToken(t.source_swap.chain,t.source_swap.asset)?this.initiateViaHTLC(a,t):this.sendViaRelayer(a,t.create_order.create_id)}catch(a){return x.Err("Error initiating swap: ",a)}}async redeem(t,r){const{secretHash:n}=Pr.from(t),i=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Pt.web3.PublicKey.findProgramAddressSync(i,this.program.programId)[0];try{const s=Uy(r),o={order_id:t.create_order.create_id,secret:Buffer.from(s).toString("hex"),perform_on:"destination"},a=await x.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify(o),headers:{"Content-Type":"application/json"}});if(a.error)return x.Err(`Redeem: Error from relayer: ${a.error}`);if(!a.result)return x.Err("Redeem: No transaction hash returned from relayer");const c=a.result;return await bd(this.provider.connection,c)?x.Ok(c):x.Err("Redeem: Timed out waiting for confirmation")}catch(s){return console.error("Redeem: Caught exception:",s),x.Err(`Error redeeming: ${s instanceof Error?s.message:String(s)}`)}}async refund(){return x.Err("Refund is automatically handled by the relayer.")}}class wf extends x.EventBroker{constructor(t){super(),this.environment=x.Environment.TESTNET,this.getOrderThreshold=20,this.refundSacpCache=new Map,this.bitcoinRedeemCache=new fx;const{api:r,environment:n}=Jc(t.environment);if(this.environment=n,this._api=r,typeof t.digestKey=="string"){const s=x.DigestKey.from(t.digestKey);if(!s.ok)throw new Error(s.error);this._digestKey=s.val}else this._digestKey=t.digestKey;this._quote=t.quote??new dy(this._api.quote),this._auth=t.auth??x.Siwe.fromDigestKey(new x.Url(this._api.auth),this._digestKey),this._orderbook=t.orderbook??new le.Orderbook(new x.Url(this._api.orderbook)),this._evmHTLC=t.htlc.evm,this._starknetHTLC=t.htlc.starknet,this._solanaHTLC=t.htlc.solana,this._secretManager=t.secretManager??Xi.fromDigestKey(this._digestKey.digestKey),this.orderExecutorCache=new ux,this._blockNumberFetcher=t.blockNumberFetcher??new fy(this._api.info,this.environment);const i=new xy(Jv(this.environment));this._btcWallet=jr.fromPrivateKey(this._digestKey.digestKey,i)}static fromWallets(t){let r;if(typeof t.digestKey=="string"){const s=x.DigestKey.from(t.digestKey);if(!s.ok)throw new Error(s.error);r=s.val}else r=t.digestKey;const{api:n}=Jc(t.environment);if(!n)throw new Error("API not found, invalid environment "+t.environment);const i={evm:t.wallets.evm?new my(n.evmRelay,t.wallets.evm,x.Siwe.fromDigestKey(new x.Url(n.auth),r)):void 0,starknet:t.wallets.starknet?new Ey(n.starknetRelay,t.wallets.starknet,t.environment===x.Environment.MAINNET?x.Network.MAINNET:x.Network.TESTNET):void 0,solana:t.wallets.solana?new Hy(t.wallets.solana,new x.Url(n.solanaRelay),t.environment===x.Environment.MAINNET?Xc.mainnet:Xc.testnet,t.solanaProgramAddress?t.solanaProgramAddress:C0.mainnet):void 0};return new wf({htlc:i,...t})}get evmHTLC(){return this._evmHTLC}get starknetHTLC(){return this._starknetHTLC}get solanaHTLC(){return this._solanaHTLC}get quote(){return this._quote}get btcWallet(){return this._btcWallet}get orderbook(){return this._orderbook}get blockNumberFetcher(){return this._blockNumberFetcher}get secretManager(){return this._secretManager}get auth(){return this._auth}get digestKey(){return this._digestKey}async swap(t){const r=await this.validateAndFillParams(t);if(!r.ok)return x.Err(r.error);const{sendAddress:n,receiveAddress:i,timelock:s}=r.val,o=Date.now().toString(),a=await this._secretManager.generateSecret(o);if(!a.ok)return x.Err(a.error);const{strategyId:c,btcAddress:f}=t.additionalData,u={strategy_id:c,...f&&{bitcoin_optional_recipient:f}},d={source_chain:t.fromAsset.chain,destination_chain:t.toAsset.chain,source_asset:t.fromAsset.atomicSwapAddress,destination_asset:t.toAsset.atomicSwapAddress,initiator_source_address:n,initiator_destination_address:i,source_amount:t.sendAmount,destination_amount:t.receiveAmount,fee:"1",nonce:o,timelock:s,secret_hash:x.trim0x(a.val.secretHash),min_destination_confirmations:t.minDestinationConfirmations??0,additional_data:u,affiliate_fees:this.withDefaultAffiliateFees(t.affiliateFee)},y=await this._quote.getAttestedQuote(d);if(!y.ok)return x.Err(y.error);const p=await this._orderbook.createOrder(y.val,this._auth);if(!p.ok)return x.Err(p.error);const g=await this.pollOrder(p.val);return g.ok?x.Ok(g.val):x.Err(g.error)}withDefaultAffiliateFees(t){return(t??[]).map(r=>({fee:r.fee,address:r.address,chain:r.chain??gd.chain,asset:r.asset??gd.asset}))}async validateAndFillParams(t){if(!t.additionalData.strategyId)return x.Err("StrategyId is required");if(!t.fromAsset||!t.toAsset)return x.Err("Source and destination assets are required for swap");if(t.fromAsset.chain===t.toAsset.chain&&t.fromAsset.atomicSwapAddress===t.toAsset.atomicSwapAddress)return x.Err("Source and destination assets cannot be the same");if(le.isMainnet(t.fromAsset.chain)&&!le.isMainnet(t.toAsset.chain)||!le.isMainnet(t.fromAsset.chain)&&le.isMainnet(t.toAsset.chain))return x.Err("Both assets should be on the same network (either mainnet or testnet)");const r=this.validateAmount(t.sendAmount);if(!r.ok)return x.Err(r.error);const n=this.validateAmount(t.receiveAmount);if(!n.ok)return x.Err(n.error);if(r<n)return x.Err("Send amount should be greater than receive amount");const i=le.getTimeLock(t.fromAsset.chain);if(!i)return x.Err("Unsupported chain for timelock");if((le.isBitcoin(t.fromAsset.chain)||le.isBitcoin(t.toAsset.chain))&&!t.additionalData.btcAddress)return x.Err("btcAddress in additionalData is required if source or destination chain is bitcoin, it is used as refund or redeem address.");const s=await this.getAddresses(t.fromAsset.chain);if(!s.ok)return x.Err(s.error);const o=await this.getAddresses(t.toAsset.chain);return o.ok?x.Ok({sendAddress:s.val,receiveAddress:o.val,timelock:t.timelock??i}):x.Err(o.error)}async getAddresses(t){var n;switch(le.getBlockchainType(t)){case le.BlockchainType.EVM:return this._evmHTLC?x.Ok(this._evmHTLC.htlcActorAddress):x.Err("Please provide evmHTLC when initializing garden");case le.BlockchainType.Bitcoin:{const i=await((n=this._btcWallet)==null?void 0:n.getPublicKey());return!i||!Zv(i)?x.Err("Invalid btc public key"):x.Ok(Ar(i))}case le.BlockchainType.Solana:return this._solanaHTLC?x.Ok(this._solanaHTLC.htlcActorAddress):x.Err("Please provide solanaHTLC when initializing garden");case le.BlockchainType.Starknet:return this._starknetHTLC?x.Ok(this._starknetHTLC.htlcActorAddress):x.Err("Please provide starknetHTLC when initializing garden");default:return x.Err("Unsupported chain")}}validateAmount(t){if(t==null||t.includes("."))return x.Err("Invalid amount ",t);const r=new Dy(t);return!r.isInteger()||r.isNaN()||r.lt(0)||r.isLessThanOrEqualTo(0)?x.Err("Invalid amount ",t):x.Ok(r)}async pollOrder(t){let r=await this._orderbook.getOrder(t,!0),n=0;for(;n<this.getOrderThreshold;){if(await x.sleep(1e3),n++,r.ok){if(r.val&&r.val.create_order.create_id.toLowerCase()===t.toLowerCase())return x.Ok(r.val)}else if(!r.error.includes("result is undefined"))return x.Err(r.error);r=await this._orderbook.getOrder(t,!0)}return x.Err(`Order not found, createOrder id: ${t}`)}async execute(t=5e3){return await this._orderbook.subscribeOrders(this._digestKey.userId,!0,t,async r=>{const n=await this.assignStatus(r.data);if(n.ok&&(this.emit("onPendingOrdersChanged",n.val),r.data.length!==0))for(let i=0;i<n.val.length;i++){const s=n.val[i],o=ef(s.status);if(le.isBitcoin(s.source_swap.chain)&&(s.status===fe.InitiateDetected||s.status===fe.Initiated||s.status===fe.CounterPartyInitiated||s.status===fe.CounterPartyInitiateDetected||s.status===fe.CounterPartyRefundDetected||s.status===fe.CounterPartyRefunded||s.status===fe.CounterPartySwapExpired||s.status===fe.Expired||s.status===fe.DeadLineExceeded)){const a=this._btcWallet;if(!a){this.emit("error",s,"BTC wallet not found");continue}await this.postRefundSACP(s,a)}switch(o){case ve.Redeem:{const a=await this._secretManager.generateSecret(s.create_order.nonce);if(!a.ok){this.emit("error",s,a.error);return}switch(le.getBlockchainType(s.destination_swap.chain)){case le.BlockchainType.EVM:{await this.evmRedeem(s,a.val.secret);break}case le.BlockchainType.Bitcoin:{const c=this.btcWallet;if(!c){this.emit("error",s,"BTC wallet not found");return}await this.btcRedeem(c,s,a.val.secret);break}case le.BlockchainType.Starknet:{await this.starknetRedeem(s,a.val.secret);break}case le.BlockchainType.Solana:await this.solRedeem(s,a.val.secret);break;default:this.emit("error",s,"Unsupported chain: "+s.destination_swap.chain)}break}case ve.Refund:{switch(le.getBlockchainType(s.source_swap.chain)){case le.BlockchainType.Solana:{this.emit("error",s,"Solana refund is automatically done by relay service");break}case le.BlockchainType.EVM:{this.emit("error",s,"EVM refund is automatically done by relay service");break}case le.BlockchainType.Bitcoin:{const a=this.btcWallet;if(!a){this.emit("error",s,"BTC wallet not found");return}await this.btcRefund(a,s);break}case le.BlockchainType.Starknet:{this.emit("error",s,"Starknet refund is automatically done by relay service");break}default:this.emit("error",s,"Unsupported chain: "+s.source_swap.chain)}break}}}},"pending",{per_page:500})}async solRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing sol redeem"),this.orderExecutorCache.get(t,ve.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._solanaHTLC){this.emit("error",t,"Solana HTLC is required");return}const i=await this._solanaHTLC.redeem(t,r);if(i.error){this.emit("error",t,i.error),i.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,ve.Redeem,t.destination_swap.redeem_tx_hash);return}i.val&&(this.orderExecutorCache.set(t,ve.Redeem,i.val),this.emit("success",t,ve.Redeem,i.val))}async evmRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing evm redeem"),this.orderExecutorCache.get(t,ve.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._evmHTLC){this.emit("error",t,"EVMHTLC is required");return}const i=await this._evmHTLC.redeem(t,r);if(!i.ok){this.emit("error",t,i.error),i.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,ve.Redeem,t.destination_swap.redeem_tx_hash);return}this.orderExecutorCache.set(t,ve.Redeem,i.val),this.emit("success",t,ve.Redeem,i.val)}async starknetRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing starknet redeem"),this.orderExecutorCache.get(t,ve.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._starknetHTLC){this.emit("error",t,"StarknetHTLC is required");return}const i=await this._starknetHTLC.redeem(t,r);if(!i.ok){this.emit("error",t,i.error),i.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,ve.Redeem,t.destination_swap.redeem_tx_hash);return}i.val&&(this.orderExecutorCache.set(t,ve.Redeem,i.val),this.emit("success",t,ve.Redeem,i.val))}async btcRedeem(t,r,n){var a,c;const i=this.bitcoinRedeemCache.get(r.create_order.create_id),s=(a=r.destination_swap.initiate_tx_hash.split(",").at(-1))==null?void 0:a.split(":").at(0);if(!s){this.emit("error",r,"Failed to get initiate_tx_hash");return}let o=!1;if(i)if(i.redeemedFromUTXO&&i.redeemedFromUTXO!==s)o=!0,this.emit("log",r.create_order.create_id,"rbf btc redeem");else if(i.redeemedAt&&Date.now()-i.redeemedAt>1e3*60*15)this.emit("log",r.create_order.create_id,"redeem not confirmed in last 15 minutes"),o=!0;else{this.emit("log",r.create_order.create_id,"btcRedeem: already redeemed");return}else if(r.destination_swap.redeem_tx_hash&&!Number(r.destination_swap.redeem_block_number))try{const f=await(await t.getProvider()).getTransaction(r.destination_swap.redeem_tx_hash);let u=!1;for(const d of f.vin)if(d.txid===s){u=!0;break}if(u){this.emit("log",r.create_order.create_id,"already a valid redeem");let d=0;try{const[y]=await(await t.getProvider()).getTransactionTimes([r.destination_swap.redeem_tx_hash]);y!==0&&(d=y)}catch{d=Date.now()}this.bitcoinRedeemCache.set(r.create_order.create_id,{redeemedFromUTXO:s,redeemedAt:d,redeemTxHash:r.destination_swap.redeem_tx_hash});return}o=!0}catch(f){if(f.message.includes("Transaction not found"))o=!0;else{this.emit("error",r,"Failed to get redeem tx: "+f);return}}this.emit("log",r.create_order.create_id,"executing btc redeem");try{const u=await(await Ei.from(t,Number(r.destination_swap.amount),r.create_order.secret_hash,Ar(r.destination_swap.initiator),Ar(r.destination_swap.redeemer),r.destination_swap.timelock,o?[s]:[])).getRedeemHex(x.trim0x(n),(c=r.create_order.additional_data)==null?void 0:c.bitcoin_optional_recipient),d=await this.broadcastRedeemTx(u,r.create_order.create_id);if(!d.ok){this.emit("error",r,d.error||"Failed to broadcast redeem tx");return}o?(this.emit("log",r.create_order.create_id,"rbf: btc redeem success"),this.emit("rbf",r,d.val)):this.emit("success",r,ve.Redeem,d.val),this.bitcoinRedeemCache.set(r.create_order.create_id,{redeemedFromUTXO:s,redeemedAt:Date.now(),redeemTxHash:d.val})}catch(f){this.emit("error",r,"Failed btc redeem: "+f)}}async btcRefund(t,r){var n;if(!this.orderExecutorCache.get(r,ve.Refund)){this.emit("log",r.create_order.create_id,"executing btc refund");try{const s=await(await Ei.from(t,Number(r.source_swap.amount),r.create_order.secret_hash,Ar(r.source_swap.initiator),Ar(r.source_swap.redeemer),r.source_swap.timelock)).refund((n=r.create_order.additional_data)==null?void 0:n.bitcoin_optional_recipient);this.orderExecutorCache.set(r,ve.Refund,s),this.emit("success",r,ve.Refund,s)}catch(i){this.emit("error",r,"Failed btc refund: "+i)}}}async postRefundSACP(t,r){const n=this.refundSacpCache.get(t.create_order.create_id);if((n==null?void 0:n.initTxHash)===t.source_swap.initiate_tx_hash)return;const i=await Ei.from(r,Number(t.source_swap.amount),t.create_order.secret_hash,Ar(t.source_swap.initiator),Ar(t.source_swap.redeemer),t.source_swap.timelock);if(t.create_order.additional_data.bitcoin_optional_recipient)try{if(!this._api)return;const o=await this._auth.getAuthHeaders();if(o.error){this.emit("error",t,"Failed to get auth headers: "+o.error);return}const a=await x.Fetcher.post(new x.Url(this._api.orderbook).endpoint("relayer/bitcoin/instant-refund-hash"),{body:JSON.stringify({order_id:t.create_order.create_id}),headers:{"Content-Type":"application/json",...o.val}});if(a.error||!a.result){this.emit("error",t,"Failed to get hash while posting instant refund SACP: "+a.error);return}const c=await i.generateInstantRefundSACPWithHash(a.result),f=new x.Url(this._api.orderbook).endpoint("relayer/bitcoin/instant-refund");(await x.Fetcher.post(f,{headers:{"Content-Type":"application/json",...o.val},body:JSON.stringify({order_id:t.create_order.create_id,signatures:c})})).status==="Ok"&&this.refundSacpCache.set(t.create_order.create_id,{initTxHash:t.source_swap.initiate_tx_hash})}catch(o){this.emit("error",t,"Failed to generate and post SACP: "+o);return}}async assignStatus(t){var i;if(t.length===0)return x.Ok([]);const r=await((i=this._blockNumberFetcher)==null?void 0:i.fetchBlockNumbers());if(!r.ok)return x.Err(r.error);const n=[];for(let s=0;s<t.length;s++){const o=t[s],a=o.source_swap.chain,c=o.destination_swap.chain,f=r==null?void 0:r.val[a],u=r==null?void 0:r.val[c];if(!f||!u){this.emit("error",o,"Error while fetching CurrentBlockNumbers");continue}const d=Qu(o,f,u);n.push({...o,status:d})}return x.Ok(n)}async broadcastRedeemTx(t,r){try{if(!this._api)return x.Err("API not found");const n=new x.Url(this._api.evmRelay).endpoint("/bitcoin/redeem "),i=await this._auth.getAuthHeaders(),o=await(await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...i.val},body:JSON.stringify({redeem_tx_bytes:t,order_id:r})})).json();return o.status==="Ok"&&o.result?x.Ok(o.result):x.Err(o.error)}catch(n){return x.Err("Failed to broadcast redeem tx: "+n)}}}class JA{constructor(t,r,n){this.callData=new $e.CallData(gy),this.account=t,this.starknetProvider=new $e.RpcProvider({nodeUrl:r||(n?Wi[n].nodeUrl:Wi.mainnet.nodeUrl)})}get htlcActorAddress(){return this.account.address}async getHTLCContract(t,r=!1){const n=r?t.destination_swap.asset:t.source_swap.asset;return new $e.Contract(vy,n,this.account)}async initiate(t){try{const n=await(await this.getHTLCContract(t)).token();if(!n)throw new Error("Token address retrieval failed");const i=$e.num.toHex(n),s=$e.cairo.uint256(BigInt(t.source_swap.amount));try{const a=await by(this.account,i,t.source_swap.asset,BigInt(t.source_swap.amount),this.starknetProvider);if(a.error)return x.Err(a.error)}catch(a){return x.Err(`Allowance check failed: ${a}`)}const o=await this.account.execute({contractAddress:t.source_swap.asset,entrypoint:"initiate",calldata:[t.source_swap.redeemer,BigInt(t.source_swap.timelock),s.low,s.high,...x.hexToU32Array(t.create_order.secret_hash)]});if(!o.transaction_hash)throw new Error("Failed to initiate HTLC transaction");return x.Ok(o.transaction_hash)}catch(r){return x.Err(`HTLC Initiation Error: ${r}`)}}async redeem(t,r){try{const n=await this.getHTLCContract(t,!0),i=t.create_order.source_chain.includes("starknet")?t.source_swap.swap_id:t.destination_swap.swap_id,s=await this.account.execute({contractAddress:n.address,entrypoint:"redeem",calldata:$e.CallData.compile({swap_id:i,secret:x.hexToU32Array(r)})});return s.transaction_hash?x.Ok(s.transaction_hash):x.Err("Failed to redeem HTLC transaction")}catch{return x.Err("HTLC Redeem Error")}}async refund(t){try{const r=t.create_order.source_chain.includes("starknet")?t.source_swap.swap_id:t.destination_swap.swap_id,n=await this.getHTLCContract(t),i=await this.account.execute({contractAddress:n.address,entrypoint:"refund",calldata:{orderId:r}});return i.transaction_hash?x.Ok(i.transaction_hash):x.Err("Failed to refund HTLC transaction")}catch{return x.Err("HTLC Refund Error")}}}class QA{constructor(t){if(this.provider=t,!t)throw new Error("Provider is required");this.provider=t,this.program=new Pt.Program(au,t)}get htlcActorAddress(){if(!this.program.programId)throw new Error("No program found");return this.provider.publicKey.toBase58()}async initiate(t){if(!t)return x.Err("Order is required");try{const{redeemer:r,secretHash:n,amount:i,expiresIn:s}=Pr.from(t),o=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Pt.web3.PublicKey.findProgramAddressSync(o,this.program.programId)[0];const a=await this.program.methods.initiate(i,s,r,n).accounts({initiator:this.provider.publicKey}).transaction(),c=await this.provider.sendAndConfirm(a);return c?x.Ok(c):x.Err("Failed to initiate HTLC transaction")}catch(r){return x.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async redeem(t,r){if(!t)return x.Err("Order is required");if(!r)return x.Err("Secret is required");const{secretHash:n}=Pr.from(t),i=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Pt.web3.PublicKey.findProgramAddressSync(i,this.program.programId)[0];try{const{redeemer:s}=Pr.from(t);if(!this.swapAccount)return x.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const o=await this.program.methods.redeem(Uy(r)).accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey,redeemer:s}).transaction(),a=await this.provider.sendAndConfirm(o);return a?x.Ok(a):x.Err("Failed to redeem HTLC transaction")}catch(s){return x.Err(`Error redeeming swap: ${s instanceof Error?s.message:String(s)}`)}}async refund(t){if(!t)return x.Err("Order is required");const{secretHash:r}=Pr.from(t),n=[Buffer.from("swap_account"),Buffer.from(r)];this.swapAccount=Pt.web3.PublicKey.findProgramAddressSync(n,this.program.programId)[0];try{if(console.log("Initiating refund for ::",t.source_swap.swap_id),!this.swapAccount)return x.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const i=await this.program.methods.refund().accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey}).transaction(),s=await this.provider.sendAndConfirm(i);return s?x.Ok(s):x.Err("Failed to refund HTLC transaction")}catch(i){return x.Err(`Error refunding swap: ${i instanceof Error?i.message:String(i)}`)}}}exports.API=Hs;exports.BaseError=D;exports.BitcoinNetwork=at;exports.BitcoinProvider=xy;exports.BitcoinWallet=jr;exports.BlockNumberFetcher=fy;exports.EvmRelay=my;exports.Garden=wf;exports.HttpRequestError=Pn;exports.OrderActions=ve;exports.OrderStatus=fe;exports.ParseOrderStatus=Qu;exports.ParseSwapStatus=nu;exports.Quote=dy;exports.STARKNET_CONFIG=Wi;exports.SecretManager=Xi;exports.SolanaHTLC=QA;exports.SolanaRelay=Hy;exports.SolanaRelayerAddress=Xc;exports.StarknetHTLC=JA;exports.StarknetRelay=Ey;exports.SwapStatus=Ee;exports.botanixMainnet=ly;exports.call=os;exports.checkAllowance=xi;exports.checkAllowanceAndApprove=by;exports.concat=ct;exports.constructOrderPair=eu;exports.decodeErrorResult=$p;exports.encodeAbiParameters=pr;exports.evmToViemChainMap=hf;exports.filterDeadlineExpiredOrders=rE;exports.getUrl=so;exports.hyperliquid=hy;exports.hyperliquidTestnet=py;exports.isAddressEqual=ss;exports.isAllowanceSufficient=wy;exports.isExpired=Ki;exports.isHex=It;exports.isOrderExpired=R0;exports.localBatchGatewayRequest=Lh;exports.localBatchGatewayUrl=vo;exports.parseAction=tE;exports.parseActionFromStatus=ef;exports.resolveApiConfig=Jc;exports.solanaProgramAddress=C0;exports.stringify=Oe;exports.switchOrAddNetwork=yy;exports.toXOnly=Ar;exports.validateBTCAddress=Xv;
99
+ `)+" "+H[1]:H[0]+N+" "+k.join(", ")+" "+H[1]}e.types=FA();function E(k){return Array.isArray(k)}e.isArray=E;function A(k){return typeof k=="boolean"}e.isBoolean=A;function P(k){return k===null}e.isNull=P;function w(k){return k==null}e.isNullOrUndefined=w;function _(k){return typeof k=="number"}e.isNumber=_;function T(k){return typeof k=="string"}e.isString=T;function I(k){return typeof k=="symbol"}e.isSymbol=I;function R(k){return k===void 0}e.isUndefined=R;function L(k){return S(k)&&V(k)==="[object RegExp]"}e.isRegExp=L,e.types.isRegExp=L;function S(k){return typeof k=="object"&&k!==null}e.isObject=S;function $(k){return S(k)&&V(k)==="[object Date]"}e.isDate=$,e.types.isDate=$;function C(k){return S(k)&&(V(k)==="[object Error]"||k instanceof Error)}e.isError=C,e.types.isNativeError=C;function U(k){return typeof k=="function"}e.isFunction=U;function j(k){return k===null||typeof k=="boolean"||typeof k=="number"||typeof k=="string"||typeof k=="symbol"||typeof k>"u"}e.isPrimitive=j,e.isBuffer=$A();function V(k){return Object.prototype.toString.call(k)}function Y(k){return k<10?"0"+k.toString(10):k.toString(10)}var X=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function J(){var k=new Date,N=[Y(k.getHours()),Y(k.getMinutes()),Y(k.getSeconds())].join(":");return[k.getDate(),X[k.getMonth()],N].join(" ")}e.log=function(){console.log("%s - %s",J(),e.format.apply(e,arguments))},e.inherits=UA(),e._extend=function(k,N){if(!N||!S(N))return k;for(var H=Object.keys(N),Z=H.length;Z--;)k[H[Z]]=N[H[Z]];return k};function M(k,N){return Object.prototype.hasOwnProperty.call(k,N)}var B=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;e.promisify=function(N){if(typeof N!="function")throw new TypeError('The "original" argument must be of type Function');if(B&&N[B]){var H=N[B];if(typeof H!="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(H,B,{value:H,enumerable:!1,writable:!1,configurable:!0}),H}function H(){for(var Z,Q,ie=new Promise(function(te,se){Z=te,Q=se}),ne=[],re=0;re<arguments.length;re++)ne.push(arguments[re]);ne.push(function(te,se){te?Q(te):Z(se)});try{N.apply(this,ne)}catch(te){Q(te)}return ie}return Object.setPrototypeOf(H,Object.getPrototypeOf(N)),B&&Object.defineProperty(H,B,{value:H,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(H,t(N))},e.promisify.custom=B;function q(k,N){if(!k){var H=new Error("Promise was rejected with a falsy value");H.reason=k,k=H}return N(k)}function W(k){if(typeof k!="function")throw new TypeError('The "original" argument must be of type Function');function N(){for(var H=[],Z=0;Z<arguments.length;Z++)H.push(arguments[Z]);var Q=H.pop();if(typeof Q!="function")throw new TypeError("The last argument must be of type Function");var ie=this,ne=function(){return Q.apply(ie,arguments)};k.apply(this,H).then(function(re){process.nextTick(ne.bind(null,null,re))},function(re){process.nextTick(q.bind(null,re,ne))})}return Object.setPrototypeOf(N,Object.getPrototypeOf(k)),Object.defineProperties(N,t(k)),N}e.callbackify=W}(ba)),ba}Object.defineProperty(zn,"__esModule",{value:!0});zn.encode=zn.decode=void 0;const Fy=Br;function HA(e){return(Fy.isBrowser?new TextDecoder("utf-8"):new(Ny()).TextDecoder("utf-8")).decode(e)}zn.decode=HA;function LA(e){return(Fy.isBrowser?new TextEncoder:new(Ny()).TextEncoder("utf-8")).encode(e)}zn.encode=LA;var qn={},cu={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */(function(e,t){var r=un,n=r.Buffer;function i(o,a){for(var c in o)a[c]=o[c]}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=s);function s(o,a,c){return n(o,a,c)}s.prototype=Object.create(n.prototype),i(n,s),s.from=function(o,a,c){if(typeof o=="number")throw new TypeError("Argument must not be a number");return n(o,a,c)},s.alloc=function(o,a,c){if(typeof o!="number")throw new TypeError("Argument must be a number");var f=n(o);return a!==void 0?typeof c=="string"?f.fill(a,c):f.fill(a):f.fill(0),f},s.allocUnsafe=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return n(o)},s.allocUnsafeSlow=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return r.SlowBuffer(o)}})(cu,cu.exports);var MA=cu.exports,Ns=MA.Buffer;function DA(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var n=0;n<e.length;n++){var i=e.charAt(n),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=n}var o=e.length,a=e.charAt(0),c=Math.log(o)/Math.log(256),f=Math.log(256)/Math.log(o);function u(p){if((Array.isArray(p)||p instanceof Uint8Array)&&(p=Ns.from(p)),!Ns.isBuffer(p))throw new TypeError("Expected Buffer");if(p.length===0)return"";for(var g=0,b=0,E=0,A=p.length;E!==A&&p[E]===0;)E++,g++;for(var P=(A-E)*f+1>>>0,w=new Uint8Array(P);E!==A;){for(var _=p[E],T=0,I=P-1;(_!==0||T<b)&&I!==-1;I--,T++)_+=256*w[I]>>>0,w[I]=_%o>>>0,_=_/o>>>0;if(_!==0)throw new Error("Non-zero carry");b=T,E++}for(var R=P-b;R!==P&&w[R]===0;)R++;for(var L=a.repeat(g);R<P;++R)L+=e.charAt(w[R]);return L}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return Ns.alloc(0);for(var g=0,b=0,E=0;p[g]===a;)b++,g++;for(var A=(p.length-g)*c+1>>>0,P=new Uint8Array(A);g<p.length;){var w=p.charCodeAt(g);if(w>255)return;var _=t[w];if(_===255)return;for(var T=0,I=A-1;(_!==0||T<E)&&I!==-1;I--,T++)_+=o*P[I]>>>0,P[I]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");E=T,g++}for(var R=A-E;R!==A&&P[R]===0;)R++;var L=Ns.allocUnsafe(b+(A-R));L.fill(0,0,b);for(var S=b;R!==A;)L[S++]=P[R++];return L}function y(p){var g=d(p);if(g)return g;throw new Error("Non-base"+o+" character")}return{encode:u,decodeUnsafe:d,decode:y}}var jA=DA,zA=jA,qA="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",GA=zA(qA),VA=Kt&&Kt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(qn,"__esModule",{value:!0});qn.decode=qn.encode=void 0;const $y=VA(GA);function WA(e){return $y.default.encode(e)}qn.encode=WA;function KA(e){return $y.default.decode(e)}qn.decode=KA;var Gn={};Object.defineProperty(Gn,"__esModule",{value:!0});Gn.decode=Gn.encode=void 0;const YA=un;function ZA(e){return e.toString("base64")}Gn.encode=ZA;function XA(e){return YA.Buffer.from(e,"base64")}Gn.decode=XA;var JA=Kt&&Kt.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),QA=Kt&&Kt.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Uo=Kt&&Kt.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&JA(t,e,r);return QA(t,e),t};Object.defineProperty(sr,"__esModule",{value:!0});sr.base64=sr.bs58=sr.utf8=Xs=sr.hex=void 0;var Xs=sr.hex=Uo(jn);sr.utf8=Uo(zn);sr.bs58=Uo(qn);sr.base64=Uo(Gn);class Pr{constructor(t,r,n,i,s){try{this.swapId=[...Xs.decode(t)],this.secretHash=[...Xs.decode(n)]}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 Pt.web3.PublicKey(r)}catch(o){throw new Error("Error decoding redeemer. Ensure it is a valid base58 encoded",{cause:o})}try{this.amount=new Pt.BN(i.toString(10),10),this.expiresIn=new Pt.BN(s)}catch(o){throw new Error("Error decoding amount. Invalid value for amount",{cause:o})}if(!(Number.isInteger(s)&&s>0))throw new Error("expiresIn must be a positive integer.")}static from(t){let r;if(t.source_swap.chain.includes("solana"))r=t.source_swap;else if(t.destination_swap.chain.includes("solana"))r=t.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:i,secret_hash:s,timelock:o}=r,a=BigInt(r.amount);return new Pr(n,i,s,a,o)}}function Uy(e){let t;try{t=[...Xs.decode(e)]}catch(r){throw new Error("Error decoding secret. Ensure it is a hex string",{cause:r})}if(t.length!=32)throw new Error("Invalid Secret size. Expected 32 bytes, got "+t.length);return t}class Hy{constructor(t,r,n,i){if(this.provider=t,this.url=r,!t)throw new Error("Provider is required");if(!r)throw new Error("Endpoint URL is required");if(!n)throw new Error("Relayer address is required");if(!i)throw new Error("Program address is required");try{this.relayer=new Pt.web3.PublicKey(n)}catch(o){throw new Error("Error decoding relayer public key. Ensure it is base58 encoded.",{cause:o})}const s={...au,metadata:{...au.metadata??{}},address:i};try{this.program=new Pt.Program(s,this.provider)}catch(o){throw new Error("Error creating Program instance. Ensure the IDL and provider are correct.",{cause:o})}}get htlcActorAddress(){if(!this.program.programId)throw new Error("No program found");return this.provider.publicKey.toBase58()}async sendViaRelayer(t,r){try{t.recentBlockhash=(await this.provider.connection.getLatestBlockhash()).blockhash,t.feePayer=this.relayer;const i=(await this.provider.wallet.signTransaction(t)).serialize({requireAllSignatures:!1}).toString("base64"),s={order_id:r,serialized_tx:i,perform_on:"source"},o=await x.Fetcher.post(this.url.endpoint("/spl-initiate"),{body:JSON.stringify(s),headers:{"Content-Type":"application/json"}});return o.error?x.Err(`Error from Relayer: ${o.error}`):o.result?x.Ok(o.result):x.Err("No result returned from relayer")}catch(n){return x.Err(`Failed to send transaction: ${n instanceof Error?n.message:String(n)}`)}}async initiateViaHTLC(t,r){if(!r)return x.Err("Order is required");try{const n=await this.provider.sendAndConfirm(t);return n?await bd(this.provider.connection,n)?x.Ok(n):x.Err("HTLC: Failed to Initiate swap, confirmation timed out"):x.Err("Failed to initiate HTLC transaction")}catch(n){return x.Err(`Error initiating swap: ${n instanceof Error?n.message:String(n)}`)}}async initiate(t){const{redeemer:r,secretHash:n,amount:i,expiresIn:s}=Pr.from(t),o=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Pt.web3.PublicKey.findProgramAddressSync(o,this.program.programId)[0];try{const a=await this.program.methods.initiate(i,s,r,n).accounts({initiator:this.provider.publicKey}).transaction();return le.isSolanaNativeToken(t.source_swap.chain,t.source_swap.asset)?this.initiateViaHTLC(a,t):this.sendViaRelayer(a,t.create_order.create_id)}catch(a){return x.Err("Error initiating swap: ",a)}}async redeem(t,r){const{secretHash:n}=Pr.from(t),i=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Pt.web3.PublicKey.findProgramAddressSync(i,this.program.programId)[0];try{const s=Uy(r),o={order_id:t.create_order.create_id,secret:Buffer.from(s).toString("hex"),perform_on:"destination"},a=await x.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify(o),headers:{"Content-Type":"application/json"}});if(a.error)return x.Err(`Redeem: Error from relayer: ${a.error}`);if(!a.result)return x.Err("Redeem: No transaction hash returned from relayer");const c=a.result;return await bd(this.provider.connection,c)?x.Ok(c):x.Err("Redeem: Timed out waiting for confirmation")}catch(s){return console.error("Redeem: Caught exception:",s),x.Err(`Error redeeming: ${s instanceof Error?s.message:String(s)}`)}}async refund(){return x.Err("Refund is automatically handled by the relayer.")}}class wf extends x.EventBroker{constructor(t){super(),this.environment=x.Environment.TESTNET,this.getOrderThreshold=20,this.refundSacpCache=new Map,this.bitcoinRedeemCache=new fx;const{api:r,environment:n}=Jc(t.environment);if(this.environment=n,this._api=r,typeof t.digestKey=="string"){const s=x.DigestKey.from(t.digestKey);if(!s.ok)throw new Error(s.error);this._digestKey=s.val}else this._digestKey=t.digestKey;this._quote=t.quote??new dy(this._api.quote),this._auth=t.auth??x.Siwe.fromDigestKey(new x.Url(this._api.auth),this._digestKey),this._orderbook=t.orderbook??new le.Orderbook(new x.Url(this._api.orderbook)),this._evmHTLC=t.htlc.evm,this._starknetHTLC=t.htlc.starknet,this._solanaHTLC=t.htlc.solana,this._secretManager=t.secretManager??Xi.fromDigestKey(this._digestKey.digestKey),this.orderExecutorCache=new ux,this._blockNumberFetcher=t.blockNumberFetcher??new fy(this._api.info,this.environment);const i=new xy(Jv(this.environment));this._btcWallet=jr.fromPrivateKey(this._digestKey.digestKey,i)}static fromWallets(t){let r;if(typeof t.digestKey=="string"){const s=x.DigestKey.from(t.digestKey);if(!s.ok)throw new Error(s.error);r=s.val}else r=t.digestKey;const{api:n}=Jc(t.environment);if(!n)throw new Error("API not found, invalid environment "+t.environment);const i={evm:t.wallets.evm?new my(n.evmRelay,t.wallets.evm,x.Siwe.fromDigestKey(new x.Url(n.auth),r)):void 0,starknet:t.wallets.starknet?new Ey(n.starknetRelay,t.wallets.starknet,t.environment===x.Environment.MAINNET?x.Network.MAINNET:x.Network.TESTNET):void 0,solana:t.wallets.solana?new Hy(t.wallets.solana,new x.Url(n.solanaRelay),t.environment===x.Environment.MAINNET?Xc.mainnet:Xc.testnet,t.solanaProgramAddress?t.solanaProgramAddress:C0.mainnet):void 0};return new wf({htlc:i,...t})}get evmHTLC(){return this._evmHTLC}get starknetHTLC(){return this._starknetHTLC}get solanaHTLC(){return this._solanaHTLC}get quote(){return this._quote}get btcWallet(){return this._btcWallet}get orderbook(){return this._orderbook}get blockNumberFetcher(){return this._blockNumberFetcher}get secretManager(){return this._secretManager}get auth(){return this._auth}get digestKey(){return this._digestKey}async swap(t){const r=await this.validateAndFillParams(t);if(!r.ok)return x.Err(r.error);const{sendAddress:n,receiveAddress:i,timelock:s}=r.val,o=Date.now().toString(),a=await this._secretManager.generateSecret(o);if(!a.ok)return x.Err(a.error);const{strategyId:c,btcAddress:f}=t.additionalData,u={strategy_id:c,...f&&{bitcoin_optional_recipient:f}},d={source_chain:t.fromAsset.chain,destination_chain:t.toAsset.chain,source_asset:t.fromAsset.atomicSwapAddress,destination_asset:t.toAsset.atomicSwapAddress,initiator_source_address:n,initiator_destination_address:i,source_amount:t.sendAmount,destination_amount:t.receiveAmount,fee:"1",nonce:o,timelock:s,secret_hash:x.trim0x(a.val.secretHash),min_destination_confirmations:t.minDestinationConfirmations??0,additional_data:u,affiliate_fees:this.withDefaultAffiliateFees(t.affiliateFee)},y=await this._quote.getAttestedQuote(d);if(!y.ok)return x.Err(y.error);const p=await this._orderbook.createOrder(y.val,this._auth);if(!p.ok)return x.Err(p.error);const g=await this.pollOrder(p.val);return g.ok?x.Ok(g.val):x.Err(g.error)}withDefaultAffiliateFees(t){return(t??[]).map(r=>({fee:r.fee,address:r.address,chain:r.chain??gd.chain,asset:r.asset??gd.asset}))}async validateAndFillParams(t){if(!t.additionalData.strategyId)return x.Err("StrategyId is required");if(!t.fromAsset||!t.toAsset)return x.Err("Source and destination assets are required for swap");if(t.fromAsset.chain===t.toAsset.chain&&t.fromAsset.atomicSwapAddress===t.toAsset.atomicSwapAddress)return x.Err("Source and destination assets cannot be the same");if(le.isMainnet(t.fromAsset.chain)&&!le.isMainnet(t.toAsset.chain)||!le.isMainnet(t.fromAsset.chain)&&le.isMainnet(t.toAsset.chain))return x.Err("Both assets should be on the same network (either mainnet or testnet)");const r=this.validateAmount(t.sendAmount);if(!r.ok)return x.Err(r.error);const n=this.validateAmount(t.receiveAmount);if(!n.ok)return x.Err(n.error);if(r<n)return x.Err("Send amount should be greater than receive amount");const i=le.getTimeLock(t.fromAsset.chain);if(!i)return x.Err("Unsupported chain for timelock");if((le.isBitcoin(t.fromAsset.chain)||le.isBitcoin(t.toAsset.chain))&&!t.additionalData.btcAddress)return x.Err("btcAddress in additionalData is required if source or destination chain is bitcoin, it is used as refund or redeem address.");const s=await this.getAddresses(t.fromAsset.chain);if(!s.ok)return x.Err(s.error);const o=await this.getAddresses(t.toAsset.chain);return o.ok?x.Ok({sendAddress:s.val,receiveAddress:o.val,timelock:t.timelock??i}):x.Err(o.error)}async getAddresses(t){var n;switch(le.getBlockchainType(t)){case le.BlockchainType.EVM:return this._evmHTLC?x.Ok(this._evmHTLC.htlcActorAddress):x.Err("Please provide evmHTLC when initializing garden");case le.BlockchainType.Bitcoin:{const i=await((n=this._btcWallet)==null?void 0:n.getPublicKey());return!i||!Zv(i)?x.Err("Invalid btc public key"):x.Ok(Ar(i))}case le.BlockchainType.Solana:return this._solanaHTLC?x.Ok(this._solanaHTLC.htlcActorAddress):x.Err("Please provide solanaHTLC when initializing garden");case le.BlockchainType.Starknet:return this._starknetHTLC?x.Ok(this._starknetHTLC.htlcActorAddress):x.Err("Please provide starknetHTLC when initializing garden");default:return x.Err("Unsupported chain")}}validateAmount(t){if(t==null||t.includes("."))return x.Err("Invalid amount ",t);const r=new Dy(t);return!r.isInteger()||r.isNaN()||r.lt(0)||r.isLessThanOrEqualTo(0)?x.Err("Invalid amount ",t):x.Ok(r)}async pollOrder(t){let r=await this._orderbook.getOrder(t,!0),n=0;for(;n<this.getOrderThreshold;){if(await x.sleep(1e3),n++,r.ok){if(r.val&&r.val.create_order.create_id.toLowerCase()===t.toLowerCase())return x.Ok(r.val)}else if(!r.error.includes("result is undefined"))return x.Err(r.error);r=await this._orderbook.getOrder(t,!0)}return x.Err(`Order not found, createOrder id: ${t}`)}async execute(t=5e3){return await this._orderbook.subscribeOrders(this._digestKey.userId,!0,t,async r=>{const n=await this.assignStatus(r.data);if(n.ok&&(this.emit("onPendingOrdersChanged",n.val),r.data.length!==0))for(let i=0;i<n.val.length;i++){const s=n.val[i],o=ef(s.status);if(le.isBitcoin(s.source_swap.chain)&&(s.status===fe.InitiateDetected||s.status===fe.Initiated||s.status===fe.CounterPartyInitiated||s.status===fe.CounterPartyInitiateDetected||s.status===fe.CounterPartyRefundDetected||s.status===fe.CounterPartyRefunded||s.status===fe.CounterPartySwapExpired||s.status===fe.Expired||s.status===fe.DeadLineExceeded)){const a=this._btcWallet;if(!a){this.emit("error",s,"BTC wallet not found");continue}await this.postRefundSACP(s,a)}switch(o){case ve.Redeem:{const a=await this._secretManager.generateSecret(s.create_order.nonce);if(!a.ok){this.emit("error",s,a.error);return}switch(le.getBlockchainType(s.destination_swap.chain)){case le.BlockchainType.EVM:{await this.evmRedeem(s,a.val.secret);break}case le.BlockchainType.Bitcoin:{const c=this.btcWallet;if(!c){this.emit("error",s,"BTC wallet not found");return}await this.btcRedeem(c,s,a.val.secret);break}case le.BlockchainType.Starknet:{await this.starknetRedeem(s,a.val.secret);break}case le.BlockchainType.Solana:await this.solRedeem(s,a.val.secret);break;default:this.emit("error",s,"Unsupported chain: "+s.destination_swap.chain)}break}case ve.Refund:{switch(le.getBlockchainType(s.source_swap.chain)){case le.BlockchainType.Solana:{this.emit("error",s,"Solana refund is automatically done by relay service");break}case le.BlockchainType.EVM:{this.emit("error",s,"EVM refund is automatically done by relay service");break}case le.BlockchainType.Bitcoin:{const a=this.btcWallet;if(!a){this.emit("error",s,"BTC wallet not found");return}await this.btcRefund(a,s);break}case le.BlockchainType.Starknet:{this.emit("error",s,"Starknet refund is automatically done by relay service");break}default:this.emit("error",s,"Unsupported chain: "+s.source_swap.chain)}break}}}},"pending",{per_page:500})}async solRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing sol redeem"),this.orderExecutorCache.get(t,ve.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._solanaHTLC){this.emit("error",t,"Solana HTLC is required");return}const i=await this._solanaHTLC.redeem(t,r);if(i.error){this.emit("error",t,i.error),i.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,ve.Redeem,t.destination_swap.redeem_tx_hash);return}i.val&&(this.orderExecutorCache.set(t,ve.Redeem,i.val),this.emit("success",t,ve.Redeem,i.val))}async evmRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing evm redeem"),this.orderExecutorCache.get(t,ve.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._evmHTLC){this.emit("error",t,"EVMHTLC is required");return}const i=await this._evmHTLC.redeem(t,r);if(!i.ok){this.emit("error",t,i.error),i.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,ve.Redeem,t.destination_swap.redeem_tx_hash);return}this.orderExecutorCache.set(t,ve.Redeem,i.val),this.emit("success",t,ve.Redeem,i.val)}async starknetRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing starknet redeem"),this.orderExecutorCache.get(t,ve.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._starknetHTLC){this.emit("error",t,"StarknetHTLC is required");return}const i=await this._starknetHTLC.redeem(t,r);if(!i.ok){this.emit("error",t,i.error),i.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,ve.Redeem,t.destination_swap.redeem_tx_hash);return}i.val&&(this.orderExecutorCache.set(t,ve.Redeem,i.val),this.emit("success",t,ve.Redeem,i.val))}async btcRedeem(t,r,n){var a,c;const i=this.bitcoinRedeemCache.get(r.create_order.create_id),s=(a=r.destination_swap.initiate_tx_hash.split(",").at(-1))==null?void 0:a.split(":").at(0);if(!s){this.emit("error",r,"Failed to get initiate_tx_hash");return}let o=!1;if(i)if(i.redeemedFromUTXO&&i.redeemedFromUTXO!==s)o=!0,this.emit("log",r.create_order.create_id,"rbf btc redeem");else if(i.redeemedAt&&Date.now()-i.redeemedAt>1e3*60*15)this.emit("log",r.create_order.create_id,"redeem not confirmed in last 15 minutes"),o=!0;else{this.emit("log",r.create_order.create_id,"btcRedeem: already redeemed");return}else if(r.destination_swap.redeem_tx_hash&&!Number(r.destination_swap.redeem_block_number))try{const f=await(await t.getProvider()).getTransaction(r.destination_swap.redeem_tx_hash);let u=!1;for(const d of f.vin)if(d.txid===s){u=!0;break}if(u){this.emit("log",r.create_order.create_id,"already a valid redeem");let d=0;try{const[y]=await(await t.getProvider()).getTransactionTimes([r.destination_swap.redeem_tx_hash]);y!==0&&(d=y)}catch{d=Date.now()}this.bitcoinRedeemCache.set(r.create_order.create_id,{redeemedFromUTXO:s,redeemedAt:d,redeemTxHash:r.destination_swap.redeem_tx_hash});return}o=!0}catch(f){if(f.message.includes("Transaction not found"))o=!0;else{this.emit("error",r,"Failed to get redeem tx: "+f);return}}this.emit("log",r.create_order.create_id,"executing btc redeem");try{const u=await(await Ei.from(t,Number(r.destination_swap.amount),r.create_order.secret_hash,Ar(r.destination_swap.initiator),Ar(r.destination_swap.redeemer),r.destination_swap.timelock,o?[s]:[])).getRedeemHex(x.trim0x(n),(c=r.create_order.additional_data)==null?void 0:c.bitcoin_optional_recipient),d=await this.broadcastRedeemTx(u,r.create_order.create_id);if(!d.ok){this.emit("error",r,d.error||"Failed to broadcast redeem tx");return}o?(this.emit("log",r.create_order.create_id,"rbf: btc redeem success"),this.emit("rbf",r,d.val)):this.emit("success",r,ve.Redeem,d.val),this.bitcoinRedeemCache.set(r.create_order.create_id,{redeemedFromUTXO:s,redeemedAt:Date.now(),redeemTxHash:d.val})}catch(f){this.emit("error",r,"Failed btc redeem: "+f)}}async btcRefund(t,r){var n;if(!this.orderExecutorCache.get(r,ve.Refund)){this.emit("log",r.create_order.create_id,"executing btc refund");try{const s=await(await Ei.from(t,Number(r.source_swap.amount),r.create_order.secret_hash,Ar(r.source_swap.initiator),Ar(r.source_swap.redeemer),r.source_swap.timelock)).refund((n=r.create_order.additional_data)==null?void 0:n.bitcoin_optional_recipient);this.orderExecutorCache.set(r,ve.Refund,s),this.emit("success",r,ve.Refund,s)}catch(i){this.emit("error",r,"Failed btc refund: "+i)}}}async postRefundSACP(t,r){const n=this.refundSacpCache.get(t.create_order.create_id);if((n==null?void 0:n.initTxHash)===t.source_swap.initiate_tx_hash)return;const i=await Ei.from(r,Number(t.source_swap.amount),t.create_order.secret_hash,Ar(t.source_swap.initiator),Ar(t.source_swap.redeemer),t.source_swap.timelock);if(t.create_order.additional_data.bitcoin_optional_recipient)try{if(!this._api)return;const o=await this._auth.getAuthHeaders();if(o.error){this.emit("error",t,"Failed to get auth headers: "+o.error);return}const a=await x.Fetcher.post(new x.Url(this._api.orderbook).endpoint("relayer/bitcoin/instant-refund-hash"),{body:JSON.stringify({order_id:t.create_order.create_id}),headers:{"Content-Type":"application/json",...o.val}});if(a.error||!a.result){this.emit("error",t,"Failed to get hash while posting instant refund SACP: "+a.error);return}const c=await i.generateInstantRefundSACPWithHash(a.result),f=new x.Url(this._api.orderbook).endpoint("relayer/bitcoin/instant-refund");(await x.Fetcher.post(f,{headers:{"Content-Type":"application/json",...o.val},body:JSON.stringify({order_id:t.create_order.create_id,signatures:c})})).status==="Ok"&&this.refundSacpCache.set(t.create_order.create_id,{initTxHash:t.source_swap.initiate_tx_hash})}catch(o){this.emit("error",t,"Failed to generate and post SACP: "+o);return}}async assignStatus(t){var i;if(t.length===0)return x.Ok([]);const r=await((i=this._blockNumberFetcher)==null?void 0:i.fetchBlockNumbers());if(!r.ok)return x.Err(r.error);const n=[];for(let s=0;s<t.length;s++){const o=t[s],a=o.source_swap.chain,c=o.destination_swap.chain,f=r==null?void 0:r.val[a],u=r==null?void 0:r.val[c];if(!f||!u){this.emit("error",o,"Error while fetching CurrentBlockNumbers");continue}const d=Qu(o,f,u);n.push({...o,status:d})}return x.Ok(n)}async broadcastRedeemTx(t,r){try{if(!this._api)return x.Err("API not found");const n=new x.Url(this._api.evmRelay).endpoint("/bitcoin/redeem "),i=await this._auth.getAuthHeaders(),o=await(await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...i.val},body:JSON.stringify({redeem_tx_bytes:t,order_id:r})})).json();return o.status==="Ok"&&o.result?x.Ok(o.result):x.Err(o.error)}catch(n){return x.Err("Failed to broadcast redeem tx: "+n)}}}class e_{constructor(t,r,n){this.callData=new $e.CallData(gy),this.account=t,this.starknetProvider=new $e.RpcProvider({nodeUrl:r||(n?Wi[n].nodeUrl:Wi.mainnet.nodeUrl)})}get htlcActorAddress(){return this.account.address}async getHTLCContract(t,r=!1){const n=r?t.destination_swap.asset:t.source_swap.asset;return new $e.Contract(vy,n,this.account)}async initiate(t){try{const n=await(await this.getHTLCContract(t)).token();if(!n)throw new Error("Token address retrieval failed");const i=$e.num.toHex(n),s=$e.cairo.uint256(BigInt(t.source_swap.amount));try{const a=await by(this.account,i,t.source_swap.asset,BigInt(t.source_swap.amount),this.starknetProvider);if(a.error)return x.Err(a.error)}catch(a){return x.Err(`Allowance check failed: ${a}`)}const o=await this.account.execute({contractAddress:t.source_swap.asset,entrypoint:"initiate",calldata:[t.source_swap.redeemer,BigInt(t.source_swap.timelock),s.low,s.high,...x.hexToU32Array(t.create_order.secret_hash)]});if(!o.transaction_hash)throw new Error("Failed to initiate HTLC transaction");return x.Ok(o.transaction_hash)}catch(r){return x.Err(`HTLC Initiation Error: ${r}`)}}async redeem(t,r){try{const n=await this.getHTLCContract(t,!0),i=t.create_order.source_chain.includes("starknet")?t.source_swap.swap_id:t.destination_swap.swap_id,s=await this.account.execute({contractAddress:n.address,entrypoint:"redeem",calldata:$e.CallData.compile({swap_id:i,secret:x.hexToU32Array(r)})});return s.transaction_hash?x.Ok(s.transaction_hash):x.Err("Failed to redeem HTLC transaction")}catch{return x.Err("HTLC Redeem Error")}}async refund(t){try{const r=t.create_order.source_chain.includes("starknet")?t.source_swap.swap_id:t.destination_swap.swap_id,n=await this.getHTLCContract(t),i=await this.account.execute({contractAddress:n.address,entrypoint:"refund",calldata:{orderId:r}});return i.transaction_hash?x.Ok(i.transaction_hash):x.Err("Failed to refund HTLC transaction")}catch{return x.Err("HTLC Refund Error")}}}class t_{constructor(t){if(this.provider=t,!t)throw new Error("Provider is required");this.provider=t,this.program=new Pt.Program(au,t)}get htlcActorAddress(){if(!this.program.programId)throw new Error("No program found");return this.provider.publicKey.toBase58()}async initiate(t){if(!t)return x.Err("Order is required");try{const{redeemer:r,secretHash:n,amount:i,expiresIn:s}=Pr.from(t),o=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Pt.web3.PublicKey.findProgramAddressSync(o,this.program.programId)[0];const a=await this.program.methods.initiate(i,s,r,n).accounts({initiator:this.provider.publicKey}).transaction(),c=await this.provider.sendAndConfirm(a);return c?x.Ok(c):x.Err("Failed to initiate HTLC transaction")}catch(r){return x.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async redeem(t,r){if(!t)return x.Err("Order is required");if(!r)return x.Err("Secret is required");const{secretHash:n}=Pr.from(t),i=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Pt.web3.PublicKey.findProgramAddressSync(i,this.program.programId)[0];try{const{redeemer:s}=Pr.from(t);if(!this.swapAccount)return x.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const o=await this.program.methods.redeem(Uy(r)).accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey,redeemer:s}).transaction(),a=await this.provider.sendAndConfirm(o);return a?x.Ok(a):x.Err("Failed to redeem HTLC transaction")}catch(s){return x.Err(`Error redeeming swap: ${s instanceof Error?s.message:String(s)}`)}}async refund(t){if(!t)return x.Err("Order is required");const{secretHash:r}=Pr.from(t),n=[Buffer.from("swap_account"),Buffer.from(r)];this.swapAccount=Pt.web3.PublicKey.findProgramAddressSync(n,this.program.programId)[0];try{if(console.log("Initiating refund for ::",t.source_swap.swap_id),!this.swapAccount)return x.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const i=await this.program.methods.refund().accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey}).transaction(),s=await this.provider.sendAndConfirm(i);return s?x.Ok(s):x.Err("Failed to refund HTLC transaction")}catch(i){return x.Err(`Error refunding swap: ${i instanceof Error?i.message:String(i)}`)}}}exports.API=Hs;exports.BaseError=D;exports.BitcoinNetwork=ct;exports.BitcoinProvider=xy;exports.BitcoinWallet=jr;exports.BlockNumberFetcher=fy;exports.EvmRelay=my;exports.Garden=wf;exports.HttpRequestError=Pn;exports.OrderActions=ve;exports.OrderStatus=fe;exports.ParseOrderStatus=Qu;exports.ParseSwapStatus=nu;exports.Quote=dy;exports.STARKNET_CONFIG=Wi;exports.SecretManager=Xi;exports.SolanaHTLC=t_;exports.SolanaRelay=Hy;exports.SolanaRelayerAddress=Xc;exports.StarknetHTLC=e_;exports.StarknetRelay=Ey;exports.SwapStatus=Ee;exports.botanixMainnet=ly;exports.call=os;exports.checkAllowance=xi;exports.checkAllowanceAndApprove=by;exports.concat=ut;exports.constructOrderPair=eu;exports.decodeErrorResult=$p;exports.encodeAbiParameters=pr;exports.evmToViemChainMap=hf;exports.filterDeadlineExpiredOrders=rE;exports.getUrl=so;exports.hyperliquid=hy;exports.hyperliquidTestnet=py;exports.isAddressEqual=ss;exports.isAllowanceSufficient=wy;exports.isExpired=Ki;exports.isHex=It;exports.isOrderExpired=R0;exports.localBatchGatewayRequest=Lh;exports.localBatchGatewayUrl=vo;exports.parseAction=tE;exports.parseActionFromStatus=ef;exports.resolveApiConfig=Jc;exports.solanaProgramAddress=C0;exports.stringify=Oe;exports.switchOrAddNetwork=yy;exports.toXOnly=Ar;exports.validateBTCAddress=Xv;